Skip to content

Commit 12b0836

Browse files
committed
450. 删除二叉搜索树中的节点 (二刷)
1 parent f85ec62 commit 12b0836

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
* @lc app=leetcode.cn id=450 lang=javascript
3+
*
4+
* [450] 删除二叉搜索树中的节点
5+
*/
6+
7+
// @lc code=start
8+
/**
9+
* Definition for a binary tree node.
10+
* function TreeNode(val, left, right) {
11+
* this.val = (val===undefined ? 0 : val)
12+
* this.left = (left===undefined ? null : left)
13+
* this.right = (right===undefined ? null : right)
14+
* }
15+
*/
16+
/**
17+
* @param {TreeNode} root
18+
* @param {number} key
19+
* @return {TreeNode}
20+
*/
21+
var deleteNode = function(root, key) {
22+
if (!root) return root;
23+
if (key > root.val) {
24+
root.right = deleteNode(root.right, key);
25+
return root;
26+
} else if (key < root.val) {
27+
root.left = deleteNode(root.left, key);
28+
return root;
29+
} else { // 找到了要删除的节点
30+
// (1). 叶节点
31+
if (!root.left && !root.right) {
32+
return null;
33+
}
34+
// (2). 只有一个孩子节点
35+
if (!root.left) {
36+
return root.right;
37+
}
38+
if (!root.right) {
39+
return root.left;
40+
}
41+
// (3). 左右孩子节点都存在
42+
// 获取右子树最小值节点
43+
const minNode = getMinNode(root.right);
44+
// 用最小值节点的值替换当前待删除几点的值
45+
root.val = minNode.val;
46+
// 删除最小值节点
47+
root.right = deleteNode(root.right, minNode.val);
48+
49+
return root;
50+
}
51+
};
52+
53+
function getMinNode(root) {
54+
while (root.left) {
55+
root = root.left;
56+
}
57+
return root;
58+
}
59+
// @lc code=end
60+

0 commit comments

Comments
 (0)