class Solution {
//法一
public TreeNode deleteNode(TreeNode root, int key) {
root = delete(root, key);
return root;
}
private TreeNode delete(TreeNode root, int key) {
if(root == null){
return null;
}
if(root.val > key){// 向左查找
root.left = delete(root.left, key);
}else if(root.val < key){// 向右查找
root.right = delete(root.right, key);
}else {// 找到要删除的结点了 即root结点
//分为三种情况,左结点为空、右结点为空、左右都不为空
if(root.left == null){
return root.right;
}
if(root.right == null){
return root.left;
}
// 如果左右结点都不为空
TreeNode tmp = root.right;//tmp用来遍历查找到大于当前root的最小值
while (tmp.left != null){
tmp = tmp.left;// 即一直迭代查找到大于当前root的最小值,即是右子树的最左边的值
}
// 这里理解为:例题图中先让4替换3 然后再删除4结点
root.val = tmp.val;// 然后把找到的tmp值赋值给root.val, 并删除掉tmp结点
root.right = delete(root.right, tmp.val);
}
return root;
}
//法二
public TreeNode deleteNode1(TreeNode root, int key) {
if(root == null){
return root;
}
if(root.val == key){
if(root.left == null){
return root.right;
}else if(root.right == null){
return root.left;
}else{
TreeNode cur = root.right;
while (cur.left != null){
cur = cur.left;
}
// 这里可以理解为:图中的2先挂在4左边 然后4替换3结点
cur.left = root.left;// root.left结点的值必定是小于cur.left的 所以这里没毛病
root = root.right;
return root;
}
}
if(root.val > key){
root.left = deleteNode1(root.left, key);
}
if(root.val < key){
root.right = deleteNode1(root.right, key);
}
return root;
}
}
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;
}
}