Solve it with java solution

  • 0

    In order to solve this problem, we need to hint that BST is a binary search tree. Binary search trees keep their keys in sorted order, so that lookup and other operations can use the principle of binary search: when looking for a key in a tree (or a place to insert a new key), they traverse the tree from root to leaf, making comparisons to keys stored in the nodes of the tree and deciding, on the basis of the comparison, to continue searching in the left or right subtrees. We need to follow up these steps:

    • We should remove the target TreeNode when the key value is equal to current root value

    • We need to do recursive when the root value is larger or smaller than the key value

    public TreeNode deleteNode(TreeNode root, int key) {
            if (root == null) {
                return root;
            if (root.val == key){
                if (root.right == null ){
                    return root.left;
                    TreeNode temp = root.right;
                    while(temp.left != null){
                        temp = temp.left;
                    int flag = root.val;
                    root.val = temp.val;
                    temp.val = flag;
            root.left = deleteNode(root.left, key);
            root.right = deleteNode(root.right, key);
            return root;

Log in to reply

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