Insert into a Binary Search Tree

Medium

You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.

Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.

For example:

 Given the tree:
         4
        / \
       2   7
      / \
     1   3
 And the value to insert: 5

You can return this BST:

          4
        /   \
       2     7
      / \   /
     1   3 5

This BST is also valid:

      5
    /   \
   2     7
  / \   
 1   3
      \
       4

Iterative Solution:

public TreeNode insertIntoBST(TreeNode root, int val) {
    if (root == null) return new TreeNode(val);
    TreeNode cur = root;
    while (true) {
        if (cur.val <= val) {
            if (cur.right != null) cur = cur.right;
            else {
                cur.right = new TreeNode(val);
                break;
            }
        } else {
            if (cur.left != null) cur = cur.left;
            else {
                cur.left = new TreeNode(val);
                break;
            }
        }
    }
    return root;
}

Iterative Solution with a stack instead of the while true:

public TreeNode insertIntoBST(TreeNode root, int val) {
    if (root == null) return new TreeNode(val);
    TreeNode current = root;
    Deque<TreeNode> stack = new ArrayDeque<>();
    stack.offerLast(root);
    while (!stack.isEmpty()) {
        current = stack.pollLast();
        if (val > current.val) {
            if (current.right == null) {
                current.right = new TreeNode(val);
                return root;
            } else {
                stack.offerLast(current.right);
            }
        } else {
            if (current.left == null) {
                current.left = new TreeNode(val);
                return root;
            } else {
                stack.offerLast(current.left);
            }
        }
    }
    return root;
}

Recursive Solution:

public TreeNode insertIntoBST(TreeNode root, int val) {
    if (root == null) {
        return new TreeNode(val);
    }
    if (val > root.val) {
        root.right = insertIntoBST(root.right, val);
    } else {
        root.left = insertIntoBST(root.left, val);
    }
    return root;
}

Categories: Binary Tree

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s