-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinsertIntoBST.ts
44 lines (36 loc) · 880 Bytes
/
insertIntoBST.ts
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
import { TreeNode } from 'classes/BinaryTreeNode'
// <Iteration, BFS>
// Time: O(n)
// Space: O(1)
// 1. bfs
function bfs(node: TreeNode, val: number): TreeNode {
let cur = node
while (cur) {
// constraints: cur.val !== val
if (val < cur.val) {
if (cur.left) {
cur = cur.left
} else {
cur.left = new TreeNode(val)
break
}
}
if (val > cur.val) {
if (cur.right) {
cur = cur.right
} else {
cur.right = new TreeNode(val)
break
}
}
}
return node
}
function insertIntoBST(root: TreeNode | null, val: number): TreeNode | null {
// edge cases
if (!root) {
return new TreeNode(val)
}
return bfs(root, val)
}
export { insertIntoBST }