Recusive Java solution O(h) time


  • 0
    G
    public TreeNode deleteNode(TreeNode root, int key) {
        if(root == null) {
            return null;
        }
        
        if(root.val < key) {
            TreeNode tmp = deleteNode(root.right, key);
            root.right = tmp;
            return root;
        } else if(root.val > key) {
            TreeNode tmp = deleteNode(root.left, key);
            root.left = tmp;
            return root;
        } else {
            return delete(root);
        }
    }
    
    public TreeNode delete(TreeNode target) {
        if(target.left == null) {
            return target.right;
        }
        
        TreeNode tmp = target.left;
        while(tmp.right != null) {
            tmp = tmp.right;
        }
        
        tmp.right = target.right;
        return target.left;
    }

Log in to reply
 

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