/**
* 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 root; //没有找到,待删除节点直接返回
if(root.val == key){//该根节点要删除
if(root.left==null&&root.right==null){ //1节点是叶子,直接删除
return null;
}else if(root.left!=null&&root.right==null){//2只有left子树,删除节点,返回左子树
return root.left;
}else if(root.right!=null&&root.left==null){//3只有right子树,返回右子树
return root.right;
}else{ //4将右子树接到原位置,左子树接到右子树左叶子
TreeNode cur = root.right; //
while(cur.left!=null) cur = cur.left; //查找右子树的左侧叶子节点
cur.left = root.left;
return root.right;
}
}
if(key<root.val) root.left = deleteNode(root.left,key);
if(key>root.val) root.right = deleteNode(root.right,key);
return root;
}
}
//迭代法
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if(root==null) return root;
TreeNode pre = null;
TreeNode cur = root;
while(cur!=null){
if(key==cur.val) break;
pre = cur;
if(key>cur.val) cur= cur.right;
else if(key<cur.val) cur = cur.left;
}
if(pre == null) return delete(cur);
if(pre.left!=null && pre.left.val==key) pre.left = delete(pre.left);
if(pre.right!=null && pre.right.val==key) pre.right = delete(pre.right);
return root;
}
public TreeNode delete(TreeNode die){
if(die==null) return null;
else if(die.left==null) return die.right;
else if(die.right==null) return die.left;
else{
TreeNode cur = die.right;
while(cur.left!=null) cur = cur.left;
cur.left = die.left;
return die.right;
}
}
}