Neat Java solution 7ms


  • 0
    T

    Find the key in the tree is the natural recursive property of BST, if the key does not exist, the recursive method will reach null node and return original tree. If the value was found, we just need a helper method to delete this node from the tree.

    public TreeNode deleteNode(TreeNode root, int key) {
        if(root==null) return null;
        if(root.val==key) return deleteHelper(root);
        if(root.val>key) root.left=deleteNode(root.left,key);
        if(root.val<key) root.right=deleteNode(root.right,key);
        return root;
    }
    TreeNode deleteHelper(TreeNode root){
        if(root.left==null&&root.right==null) return null;
        if(root.left==null) return root.right;
        if(root.right==null) return root.left;
        TreeNode cur=root.left;
        while(cur.right!=null) cur=cur.right;
        cur.right=root.right;
        return  root.left;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.