-
Notifications
You must be signed in to change notification settings - Fork 156
/
Copy pathbinary-search-tree-ii-insert.js
65 lines (57 loc) · 1.12 KB
/
binary-search-tree-ii-insert.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
60
61
62
63
64
65
/**
* Binary Search Tree - Insert
*/
import TreeNode from 'common/tree-node';
/**
* Recursion
*
* @param {TreeNode} root
* @param {number} key
* @return {TreeNode}
*/
export const insert = (root, key) => {
// If the tree is empty, return a new node
if (!root) {
return new TreeNode(key);
}
// Otherwise, recur down the tree
if (key < root.val) {
root.left = insert(root.left, key);
} else if (key > root.val) {
root.right = insert(root.right, key);
}
// Return the (unchanged) node pointer
return root;
};
/**
* Iterative
*
* @param {TreeNode} root
* @param {number} key
* @return {TreeNode}
*/
export const insertNode = (root, key) => {
const newNode = new TreeNode(key);
while (root) {
if (root.val === key) {
return root;
}
if (key < root.val) {
if (!root.left) {
root.left = newNode;
break;
} else {
root = root.left;
}
} else {
if (!root.right) {
root.right = newNode;
break;
} else {
root = root.right;
}
}
}
// If the tree is empty, return a new node
return newNode;
};