450. 删除二叉搜索树中的节点

 

 

class Solution {
    public TreeNode deleteNode(TreeNode root, int key) { 
        if(root == null) return null;
        if(root.val == key) {
            if(root.left == null) {
                return root.right;
            } else if (root.right == null) {
                return root.left;
            } else {  // 左右子树都不为null,将左子树连到,右子树的最左节点,返回右子树根节点
             // 也可将右子树连到,左子树的最右节点,返回左子树的根节点
TreeNode node = root.right; while(node.left != null) { node = node.left; } node.left = root.left; return root.right; } } if(root.val > key) { root.left = deleteNode(root.left,key); // 递归去左子树删除节点 } else { root.right = deleteNode(root.right,key); // 递归去右子树删除节点 } return root; // 返回删除操作之后子树的根节点 } }

 

posted @ 2020-07-13 09:46  Sexyomaru  阅读(116)  评论(0)    收藏  举报