Skip to content

Commit c976c2f

Browse files
committed
feat(450): 递归+BST
1 parent 5f68b37 commit c976c2f

File tree

1 file changed

+15
-24
lines changed

1 file changed

+15
-24
lines changed

Binary-Tree/450/solution1.js

Lines changed: 15 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,29 @@
11
/**
2-
* https://leetcode-cn.com/problems/delete-node-in-a-bst/
3-
*
4-
* 450. 删除二叉搜索树中的节点
5-
*
6-
* Medium
7-
*
8-
* 116ms 100%
9-
* 42.3mb 30.00%
10-
*
2+
* 时间复杂度:O(n)
3+
* 空间复杂度:O(n)
114
*/
12-
const deleteNode = (root, key) => {
5+
const deleteNode = (root, key) => {
136
if (!root) {
14-
return null
7+
return null;
158
}
169

17-
const rootValue = root.val
18-
19-
if (rootValue > key) {
20-
root.left = deleteNode(root.left, key)
21-
} else if (rootValue < key) {
22-
root.right = deleteNode(root.right, key)
10+
const rootVal = root.val;
11+
if (rootVal > key) {
12+
root.left = deleteNode(root.left, key);
13+
} else if (rootVal < key) {
14+
root.right = deleteNode(root.right, key);
2315
} else {
2416
if (root.left && root.right) {
25-
// 找一个最小的替换当前根节点,再删除这个替换的节点。
26-
let min = root.right
17+
let min = root.right;
2718
while (min.left) {
28-
min = min.left
19+
min = min.left;
2920
}
30-
root.val = min.val
31-
root.right = deleteNode(root.right, min.val)
21+
root.val = min.val;
22+
root.right = deleteNode(root.right, min.val);
3223
} else {
33-
return root.left ? root.left : root.right
24+
return root.left ? root.left : root.right;
3425
}
3526
}
3627

37-
return root
28+
return root;
3829
}

0 commit comments

Comments
 (0)