Insert into a BST

Add a new value to a binary search tree by walking down to the empty spot where it belongs.

Given the root of a binary search tree (BST) and a number val that is not in the tree yet, add val to the tree and return its root. The result must still be a binary search tree. If there is more than one way to do that, any of them is accepted.

The examples write a tree in level order: row by row from the top, each row from left to right, with null for an empty spot.

Example 1
Input: root = [4, 2, 7, 1, 3], val = 5
Output: [4, 2, 7, 1, 3, 5]
Explanation: 5 becomes the left child of 7.
Example 2
Input: root = [40, 20, 60, 10, 30, 50, 70], val = 25
Output: [40, 20, 60, 10, 30, 50, 70, null, null, 25]
Explanation: 25 becomes the left child of 30.
Solution

The Idea

A binary search tree keeps its numbers in order, a bit like a well-sorted bookshelf where you always know which way to look. Each node of the tree holds one number and has at most two children, a left one and a right one. A node's left subtree, the left child together with everything below it, holds only smaller numbers. Its right subtree holds only larger ones.

Take the tree from Example 2. The root is 40. Below it, 20 is on the left and 60 on the right. Below 20 are 10 and 30, and below 60 are 50 and 70. Every number left of 40 is smaller than 40, and every number right of it is larger. The same holds at 20 and at 60.

Now 25 has to go in. Where can it go so that this order still holds everywhere? Moving existing nodes around would work, but it is easy to break the order that way. Is there a place where 25 fits without moving anything?

There is: the place where a search for 25 would end. Look at the picture below.

The tree 40, 20, 60, 10, 30, 50, 70. At 40: 25 < 40, go left. At 20: 25 > 20, go right. At 30: 25 < 30, go left, to an empty spot where the new node 25 goes.

The search starts at the root. At 40 the note says "25 < 40: go left", so it moves to 20. At 20, "25 > 20: go right" takes it to 30. At 30, "25 < 30: go left" points at a spot with no node in it. The dashed circle marks that empty spot, where the new node 25 goes.

Why is that spot safe? 25 is smaller than 40 and sits left of 40. It is larger than 20 and sits right of 20. It is smaller than 30 and sits left of 30. Every node above it agrees with where it is, because each turn on the way down was chosen by comparing with that very node. No other node moves, so the rest of the tree keeps its order.

So inserting into a BST is a search that runs until it falls off the tree, and the new number becomes a leaf, a node with no children, right where it fell off. Example 1 works the same way: 5 is larger than 4, so go right to 7, then smaller than 7, so go left, and the left spot under 7 is empty.

Solution Approach

Turning that idea into code means settling how to walk down to the empty spot and how to link the new node to the node above it. The walk can also be written as a plain loop, as an option.

Walking down to the empty spot

Which way should the walk go at each node? Compare val with the node's value: smaller goes left, larger goes right. The problem promises that val is not in the tree yet, so the two are never equal.

A slower way would be to collect every number, add val, sort, and build a new tree. That touches every node in the tree. The walk touches only the nodes on one path from the root down, one node per row of the tree.

Linking the new node to its parent

Once the walk reaches the empty spot and makes the new node, how does the node above it, its parent, learn about it? Something has to write the new node into the parent's left or right field.

A recursive method, one that calls itself on a smaller part of the tree, handles this neatly. Let the method take the root of a subtree and return the root of that subtree after the insert. At an empty spot, it returns the new node. Everywhere else, it returns the node it was given.

Each node then stores whatever the call on its child returns back into that child field. At 30, the call on the empty left spot returns the new 25, and 30 stores it in left. At 20 and at 40, the calls return 30 and 20, the children they already had, so storing them changes nothing. An empty tree is covered too: the very first call is on an empty spot, so the new node becomes the root.

A loop instead of recursion (optional)

Can the walk do without the method calling itself? Yes. Keep a variable for the current node and move it down with the same comparisons. Stop at the node whose child on the chosen side is null, and put the new node there. The loop leaves no unfinished calls behind as it goes down, so its extra space stays constant. An empty tree needs its own check, though.

Java Solution

The method insertIntoBST works in these steps:

  1. First, check whether root is null. If it is, the walk has reached an empty spot, so return new TreeNode(val). For an empty tree, this new node is the whole tree.
  2. Otherwise compare val with root.val. If val is smaller, call insertIntoBST on root.left and store what it returns back into root.left.
  3. If val is larger, do the same on the right side: root.right = insertIntoBST(root.right, val).
  4. Return root, so the call one level up stores the same node it already had.

Around the method, a small TreeNode class holds one node, build makes a tree from level order like the examples, and show writes a tree back in level order.

The main method runs both examples, inserts 5 into an empty tree, and inserts 0, smaller than every number in Example 1's tree. Last, it builds a tree from nothing by inserting 3, 1, 4 and 2 one after another.

Java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

public class InsertIntoBST {

    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    public static TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) {
            return new TreeNode(val);          // the empty spot: the new node goes here
        }
        if (val < root.val) {
            root.left = insertIntoBST(root.left, val);    // keep the link to the left subtree
        } else {
            root.right = insertIntoBST(root.right, val);  // keep the link to the right subtree
        }
        return root;
    }

    // Builds a tree from level order, where null marks an empty spot.
    static TreeNode build(Integer... values) {
        TreeNode root = new TreeNode(values[0]);
        Queue<TreeNode> queue = new ArrayDeque<>(List.of(root));
        for (int i = 1; i < values.length; i += 2) {
            TreeNode node = queue.poll();
            if (values[i] != null) queue.add(node.left = new TreeNode(values[i]));
            if (i + 1 < values.length && values[i + 1] != null) {
                queue.add(node.right = new TreeNode(values[i + 1]));
            }
        }
        return root;
    }

    // Writes a tree in level order, the same way the examples do.
    static String show(TreeNode root) {
        List<Integer> out = new ArrayList<>();
        List<TreeNode> level = root == null ? List.of() : List.of(root);
        while (!level.isEmpty()) {
            List<TreeNode> next = new ArrayList<>();
            for (TreeNode node : level) {
                out.add(node == null ? null : node.val);
                if (node != null) {
                    next.add(node.left);
                    next.add(node.right);
                }
            }
            level = next;
        }
        while (!out.isEmpty() && out.get(out.size() - 1) == null) out.remove(out.size() - 1);
        return out.toString();
    }

    public static void main(String[] args) {
        System.out.println(show(insertIntoBST(build(4, 2, 7, 1, 3), 5)));
        System.out.println(show(insertIntoBST(build(40, 20, 60, 10, 30, 50, 70), 25)));
        System.out.println(show(insertIntoBST(null, 5)));
        System.out.println(show(insertIntoBST(build(4, 2, 7, 1, 3), 0)));
        TreeNode root = null;
        for (int v : new int[] {3, 1, 4, 2}) {
            root = insertIntoBST(root, v);
        }
        System.out.println(show(root));
    }
}

Running it prints:

Output
[4, 2, 7, 1, 3, 5]
[40, 20, 60, 10, 30, 50, 70, null, null, 25]
[5]
[4, 2, 7, 1, 3, null, null, 0]
[3, 1, 4, null, 2]

The second line, [40, 20, 60, 10, 30, 50, 70, null, null, 25], is the tree from the picture. The two nulls are the empty children of 10, and 25 comes next as the left child of 30. The third line, [5], shows the empty tree case: the first call lands on an empty spot and the new node becomes the root.

In [4, 2, 7, 1, 3, null, null, 0], the 0 went left three times, past 4, 2 and 1, and became the left child of 1. The last line, [3, 1, 4, null, 2], is a tree built only by inserts. 3 became the root, and 1 and 4 went left and right of it. Then 2 went left of 3 and right of 1.

The assignments root.left = ... and root.right = ... are what attach the new node. A copy of the program that only calls insertIntoBST(root.left, val) and insertIntoBST(root.right, val), without storing the result, prints [4, 2, 7, 1, 3] for Example 1. The new node 5 is made, but no parent points to it, so it is lost. The empty-tree line still prints [5], because there the new node is returned straight to main.

Complexity

The method follows a single path from the root down to an empty spot, with one comparison at each node on it.

  • Time: O(h), where h is the height of the tree, the number of rows from the root to the lowest leaf. The walk visits at most one node per row before it falls off the tree. For a tree of n nodes with balanced sides, h is about log2 n. Numbers inserted in increasing order make one long chain instead, with h equal to n.
  • Space: O(h) for the recursion, because one call waits at each node on the path until the call below it returns. The loop version from Solution Approach needs only O(1) extra space.

Removing a node is harder, because the gap it leaves must be filled: see Delete Node in a BST.