/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} key
* @return {TreeNode}
*/
var deleteNode = function(root, key) {
if(!root){
return null;
}
if(root.val == key){
//find the node
if(!root.left){
return root.right;
}else if(!root.right){
return root.left;
}else if (root.left&&root.right){
//find most left node;
let prev = root;
let next = root.right;
while(next.left){
prev = next;
next = next.left;
}
//此时next就是当前右子树的最左节点
root.val = next.val;
if(prev==root){
prev.right = next.right;
}else{
prev.left = next.right;
}
}
}else{
if(key<root.val){
root.left = deleteNode(root.left,key)
}else{
root.right = deleteNode(root.right,key)
}
}
return root;
};