4 cases:

1: target Node has NO child.

2: target Node has NO left child, return right child.

3: target Node has NO right child, return left child.

4: target Node has both left child and right child;

 two ways of reconstructing, left sub\(largest of the left sub\) and **right sub\(smallest of the right sub\)**

4.1 right sub has no left child, root.right.left = root.left 

 4.2 right sub has left child, we need to 一路向左 find the smallest left child to return.
public TreeNode delete(TreeNode root, int target) {
    if (root == null) {
        return null;
    }
    //find the target node.
    if (root.val < target) {
        root.right = delete(root.right, target);
        return root;
    }
    if (root.val > target) {
        root.left = delete(root.left, target);
        return root;
    }

    //case 2
    if (root.left == null) {
        return root.right;
    }
    //case 3
    if (root.right == null) {
        return root.left;
    }
    //case 4.1
    if (root.right.left == null) {
        root.right.left == root.left;
        return root.right;
    }

    //case 4.2
    TreeNode smallest = getSmallest(root.right);
    smallest.left = root.left;
    smallest.right = root.right;

    return smallest;
}

private TreeNode getSmallest(TreeNode cur) {
    TreeNode prev = cur;
    cur = cur.left;
    while (cur != null) {
        prev = cur;
        cur = cur.left;
    }
    prev.left = prev.left.right;
    return cur;
}

results matching ""

    No results matching ""