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 valval
The examples write a tree in level order: row by row from the top, each row from left to right, with null
Example 1
Output: [4, 2, 7, 1, 3, 5]
Explanation: 5 becomes the left child of 7.
Example 2
Output: [40, 20, 60, 10, 30, 50, 70, null, null, 25]
Explanation: 25 becomes the left child of 30.
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 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 valval
A slower way would be to collect every number, add val
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 leftright
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
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
Java Solution
The method insertIntoBST
- First, check whether
isroot . If it is, the walk has reached an empty spot, so returnnull . For an empty tree, this new node is the whole tree.new TreeNode(val) - Otherwise compare
withval . Ifroot.val is smaller, callval oninsertIntoBST and store what it returns back intoroot.left .root.left - If
is larger, do the same on the right side:val .root.right = insertIntoBST(root.right, val) - Return
, so the call one level up stores the same node it already had.root
Around the method, a small TreeNodebuildshow
The main
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:
[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]null[5]
In [4, 2, 7, 1, 3, null, null, 0][3, 1, 4, null, 2]
The assignments root.left = ...root.right = ...insertIntoBST(root.left, val)insertIntoBST(root.right, val)[4, 2, 7, 1, 3][5]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