#How do you understand this code, BinarySearch Delete

9 messages · Page 1 of 1 (latest)

molten delta
#

Is my guess correct?

hushed trailBOT
#

This post has been reserved for your question.

Hey @molten delta! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

molten delta
#

How do you understand this code, BinarySearch Delete

#

    // Given a binary search tree and a key, this function deletes the key and returns the new root
    Node deleteNode(Node root, int key) {
        // Base case
        if (root == null) {
            return root;
        }

        // If the key to be deleted is smaller than the root's key, then it lies in the left subtree
        if (key < root.key) {
            root.left = deleteNode(root.left, key);
        }
        // If the key to be deleted is greater than the root's key, then it lies in the right subtree
        else if (key > root.key) {
            root.right = deleteNode(root.right, key);
        }
        // If key is same as root's key, then this is the node to be deleted
        else {
            // Node with only one child or no child
            if (root.left == null) {
                return root.right;
            } else if (root.right == null) {
                return root.left;
            }

            // Node with two children: Get the inorder successor (smallest in the right subtree)
            root.key = minValue(root.right);

            // Delete the inorder successor
            root.right = deleteNode(root.right, root.key);
        }

        return root;
    }

    int minValue(Node root) {
        int minv = root.key;
        while (root.left != null) {
            minv = root.left.key;
            root = root.left;
        }
        return minv;
    }
#

So if delete 50, the new root will be 60?

molten delta
#

Aight

#

I figured it out