Skip to content

Commit a9b127b

Browse files
committed
create: 0450-delete-node-in-a-bst.ts
1 parent 914ca1f commit a9b127b

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* class TreeNode {
4+
* val: number
5+
* left: TreeNode | null
6+
* right: TreeNode | null
7+
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
8+
* this.val = (val===undefined ? 0 : val)
9+
* this.left = (left===undefined ? null : left)
10+
* this.right = (right===undefined ? null : right)
11+
* }
12+
* }
13+
*/
14+
15+
function deleteNode(root: TreeNode | null, key: number): TreeNode | null {
16+
if (!root) {
17+
return root;
18+
}
19+
20+
if (key > root.val) {
21+
root.right = deleteNode(root.right, key);
22+
} else if (key < root.val) {
23+
root.left = deleteNode(root.left, key);
24+
} else {
25+
if (!root.right) {
26+
return root.left;
27+
} else if (!root.left) {
28+
return root.right;
29+
} else {
30+
let minNode = minValueNode(root.right);
31+
root.val = minNode.val;
32+
root.right = deleteNode(root.right, minNode.val);
33+
}
34+
}
35+
return root;
36+
}
37+
38+
function minValueNode(root: TreeNode): TreeNode {
39+
let curr: TreeNode = root;
40+
while (curr && curr.left) {
41+
curr = curr.left;
42+
}
43+
return curr;
44+
}

0 commit comments

Comments
 (0)