Simple Java recursive solution


  • 0
    U
        public TreeNode deleteNode(TreeNode root, int key) {
            if (root == null) {
                return null;
            }
            
            if (root.val == key) {
                return deleteRoot(root);
            } else if (root.val > key) {
                root.left = deleteNode(root.left, key);
            } else {
                root.right = deleteNode(root.right, key);
            }
            return root;
        }
        
        TreeNode deleteRoot(TreeNode root) {
            if (root.left == null) {
                return root.right;
            } else {
                if (root.right == null) {
                    return root.left;
                }
                TreeNode node = root.left;
                while (node.right != null) {
                    node = node.right;    
                }
                node.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.