|
1 | 1 | function deleteNode(root: TreeNode | null, key: number): TreeNode | null { |
2 | | - if (root === null) return root; |
3 | | - if (root.val === key) { |
4 | | - const { left, right } = root; |
5 | | - if (left === null) return right; |
6 | | - else if (right === null) return left; |
7 | | - let ptr = left; |
8 | | - while (ptr.right !== null) ptr = ptr.right; |
9 | | - ptr.right = right; |
10 | | - return left; |
11 | | - } else if (root.left && root.left.val === key) { |
12 | | - const { left, right } = root.left; |
13 | | - if (left === null) root.left = right; |
14 | | - else { |
15 | | - let ptr = left; |
16 | | - while (ptr.right !== null) ptr = ptr.right; |
17 | | - ptr.right = right; |
18 | | - root.left = left; |
19 | | - } |
20 | | - } else if (root.right && root.right.val === key) { |
21 | | - const { left, right } = root.right; |
22 | | - if (left === null) root.right = right; |
23 | | - else { |
24 | | - let ptr = left; |
25 | | - while (ptr.right !== null) ptr = ptr.right; |
26 | | - ptr.right = right; |
27 | | - root.right = left; |
28 | | - } |
29 | | - } else if (root.val < key) { |
30 | | - root.right = deleteNode(root.right, key); |
31 | | - } else { |
| 2 | + // case 0. nothing to kill |
| 3 | + if (root === null) return null; |
| 4 | + |
| 5 | + // case 1. key in the root.left |
| 6 | + if (key < root.val) { |
32 | 7 | root.left = deleteNode(root.left, key); |
| 8 | + return root; |
| 9 | + } |
| 10 | + |
| 11 | + // case 2. key in the root.right |
| 12 | + if (key > root.val) { |
| 13 | + root.right = deleteNode(root.right, key); |
| 14 | + return root; |
33 | 15 | } |
| 16 | + |
| 17 | + // case 3. root is the key |
| 18 | + const left = root.left, |
| 19 | + right = root.right; |
| 20 | + |
| 21 | + if (left === null) return right; |
| 22 | + if (right === null) return left; |
| 23 | + |
| 24 | + // so we need to remove the root, and choose a new root val |
| 25 | + // from left's right-most (or right's left-most) |
| 26 | + let ptr = left; |
| 27 | + while (ptr.right !== null) ptr = ptr.right; |
| 28 | + |
| 29 | + root.val = ptr.val; |
| 30 | + root.left = deleteNode(left, ptr.val); // since we pick the left's rightmost, recursion kill this picked node |
| 31 | + |
34 | 32 | return root; |
35 | 33 | } |
0 commit comments