-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarySearchTree.js
More file actions
57 lines (38 loc) · 1.14 KB
/
binarySearchTree.js
File metadata and controls
57 lines (38 loc) · 1.14 KB
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
/**
In this excercise we will be creating a class for a Binary Search Tree. This class will allow us to:
1. Insert values iwth the insert method.
2. Search values with the contains method.
3. Remove values with the remove method; this method will only remove the first instance of a given value.
**/
class BST {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
/** Leet Code BST
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]
**/
var searchBST = function(root, val) {
if (!root){
return null;
}
let currentNode = root
while(currentNode) {
if(val < currentNode.val) {
//Left
currentNode = currentNode.left;
} else if(val > currentNode.val) {
//Right
currentNode = currentNode.right;
} else if(currentNode.val === val) {
return currentNode;
}
}
return null;
};