LC.P450[删除二叉搜索树中的节点]

方法一:从当前节点的左子树中选择值最大的节点代替root

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) return null;
if (root.val < key) root.right = deleteNode(root.right, key);
else if (root.val > key) root.left = deleteNode(root.left, key);
else {
if (root.left == null) return root.right;
if (root.right == null) return root.left;
// 寻找当前节点的左子树中的最大值
TreeNode t = root.left;
while (t.right != null) t = t.right;
// 将当前节点的右子树直接作为 t 的右子树
t.right = root.right;
return root.left;
}
return root;
}
}
  • 时间复杂度:$O(h)$,$h$为树的深度
  • 空间复杂度:$O(h)$

方法二:从当前节点的右子树中选择值最小的节点代替root

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) return null;
if (root.val < key) root.right = deleteNode(root.right, key);
else if (root.val > key) root.left = deleteNode(root.left, key);
else {
if (root.left == null) return root.right;
if (root.right == null) return root.left;
// 寻找当前节点的右子树中的最小值
TreeNode t = root.right;
while (t.left != null) t = t.left;
// 将当前节点的左子树直接作为 t 的左子树
t.left = root.left;
return root.right;
}
return root;
}
}
  • 时间复杂度:$O(h)$,$h$为树的深度
  • 空间复杂度:$O(h)$