yet another solution


  • 0
    J
    class Solution {
        
        boolean alreadyDeleted = false;
        
        public TreeNode deleteNode(TreeNode root, int key) {
            if (root == null) {
                return null;
            }
            
            if (root.val == key) {
                // Set flag to avoid unnecessary recursions.
                alreadyDeleted = true;
                return deleteRoot(root);
            }
            
            if (!alreadyDeleted) {
                root.left = deleteNode(root.left, key);
            }
            
            if (!alreadyDeleted) {
                root.right = deleteNode(root.right, key);
            }
            
            return root;
        }
    
        private TreeNode deleteRoot(TreeNode node) {
            if (node.left != null && node.right != null) {
                // Add .left subtree to the .right subtree (it'll always be leftmost there)
                leftmostAdd(node.right, node.left);
                // And return .right
                return node.right;
            } else if (node.left != null) {
                return node.left;
            } else if (node.right != null) {
                return node.right;
            } else {
                return null;
            }
        }
        
        private void leftmostAdd(TreeNode recipient, TreeNode donor) {
            if (recipient.left == null) {
                recipient.left = donor;
                return;
            } 
            leftmostAdd(recipient.left, donor);
        }
    }
    

Log in to reply
 

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