-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsearch-a-node.js
59 lines (34 loc) · 1020 Bytes
/
search-a-node.js
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
You are given the root of a binary search tree (BST) and an integer val.
Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null.
Example 1:
Input: root = [4,2,7,1,3], val = 2
Output: [2,1,3]
Example 2:
Input: root = [4,2,7,1,3], val = 5
Output: []
*/
var searchBST = function(root, val) {
let queue = [];
let node = root;
queue.push(node);
while(queue.length) {
node = queue.shift();
if(node.val == val) {
return node;
}
if(node.left) queue.push(node.left);
if(node.right) queue.push(node.right);
}
return null;
};
// Using depth first search
var searchBST = function(root, val) {
if(!root) return null;
if(root.val === val) return root;
let leftVal = searchBST(root.left, val);
if(leftVal) return leftVal;
let rightVal = searchBST(root.right, val);
if(rightVal) return rightVal;
return null;
};