-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0450-delete-node-in-a-bst.ts
44 lines (41 loc) · 1.16 KB
/
0450-delete-node-in-a-bst.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
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function deleteNode(root: TreeNode | null, key: number): TreeNode | null {
if (!root) {
return root;
}
if (key > root.val) {
root.right = deleteNode(root.right, key);
} else if (key < root.val) {
root.left = deleteNode(root.left, key);
} else {
if (!root.right) {
return root.left;
} else if (!root.left) {
return root.right;
} else {
let minNode = minValueNode(root.right);
root.val = minNode.val;
root.right = deleteNode(root.right, minNode.val);
}
}
return root;
}
function minValueNode(root: TreeNode): TreeNode {
let curr: TreeNode = root;
while (curr && curr.left) {
curr = curr.left;
}
return curr;
}