lt.450. 删除二叉搜索树中的节点
[案例需求]

[思路分析一, 递归法]
- 不存在该节点, 遍历到了树的末尾. root == null;
2. 存在该节点
2.1 该节点的左子树, 右子树均为空, root置为null即可;
2.2 该节点存在左子树, 直接root的直接左孩子节点代替root即可, 然后把这个节点删除
2.3 该节点存在右子树, 直接root的直接右孩子节点代替root即可. 然后把这个节点删除
[代码实现]
class Solution {
public int rightMin(TreeNode root) {
root = root.right;
while (root.left != null) root = root.left;
return root.val;
}
public int leftMax(TreeNode root) {
root = root.left;
while (root.right != null) root = root.right;
return root.val;
}
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) {
return null;
}
if (key > root.val) {
root.right = deleteNode(root.right, key);
} else if (key < root.val) {
root.left = deleteNode(root.left, key);
} else {
if (root.left == null && root.right == null) {
root = null;
} else if (root.right != null) {
root.val = rightMin(root);
root.right = deleteNode(root.right, root.val);
} else {
root.val = leftMax(root);
root.left = deleteNode(root.left, root.val);
}
}
return root;
}
}
[思路分析二, 迭代法]
[代码实现]