Java Easy to Understand Solution

  • 10
        public TreeNode deleteNode(TreeNode root, int key) {
            if (root == null) return root;
            if (root.val > key) root.left = deleteNode(root.left, key);
            else if (root.val < key) root.right = deleteNode(root.right, key);
            else { // found node to be deleted
                if (root.left == null) return root.right;
                else if (root.right == null) return root.left;
                // node with two children, replace with the inOrder successor(minVal) in the right subtree
                root.val = getMin(root.right);
                root.right = deleteNode(root.right, root.val);
            return root;
        private int getMin(TreeNode root) {
            int min = root.val;
            while (root.left != null) {
                root = root.left;
                min = root.val;
            return min;

  • 1

    i like your code format !~!

  • 3

    @Shevchenko_7 I think it can be more concise for the getMin()

        private int getMin(TreeNode root) {
            while (root.left != null) {root = root.left;}
            return root.val;

  • 0

    huh.. this is the concept - when you found the node to delete, replace the value of the node with the available minimum value (min), then recursively delete that min value.

    nice solution :)

Log in to reply

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