-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbst.js
More file actions
40 lines (32 loc) · 1010 Bytes
/
Copy pathbst.js
File metadata and controls
40 lines (32 loc) · 1010 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} k
* @return {boolean}
*/
var findTarget = function findSum(root, k) {
// Create an empty set to store values of BST nodes
let set = new Set();
// Perform inorder traversal of the BST
function inorder(root) {
// Base case: return if root is null
if (!root) return false;
// Recursively traverse left subtree
if (inorder(root.left)) return true;
// Check if k - root.val exists in the set
if (set.has(k - root.val)) return true;
// Add root.val to the set
set.add(root.val);
// Recursively traverse right subtree
return inorder(root.right);
}
// Return result of inorder traversal
return inorder(root);
}