-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeleteNode.ts
50 lines (38 loc) · 1013 Bytes
/
deleteNode.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
45
46
47
48
49
50
import { TreeNode } from 'classes/BinaryTreeNode'
// <Recursion, DFS>
// Time: O(n)
// Space: O(n)
function deleteNode(root: TreeNode | null, key: number): TreeNode | null {
// edge cases
if (!root) {
return root
}
// 1. dfs
if (root.val > key) {
root.left = deleteNode(root.left, key)
return root
}
if (root.val < key) {
root.right = deleteNode(root.right, key)
return root
}
// if (root.val === key) @below
if (!root.left && !root.right) {
return null
}
if (!root.left) {
return root.right
}
if (!root.right) {
return root.left
}
let successor = root.right
while (successor.left) {
successor = successor.left // find the minimum node in the right subtree
}
root.right = deleteNode(root.right, successor.val) // replace the root and delete it
successor.left = root.left
successor.right = root.right
return successor
}
export { deleteNode }