Given the root of a binary search tree and a value val to insert, insert it and return the root of the (still valid) BST. The value is guaranteed not to already exist. Any valid BST resulting from the insertion is accepted, but a natural insert always creates a new leaf.
The tree is given/returned in level-order (breadth-first), using null for missing children.
Input: root = [4, 2, 7, 1, 3], val = 5 Output: [4, 2, 7, 1, 3, 5] 5 is inserted as the left child of 7.
Input: root = [], val = 5 Output: [5] Into an empty tree, the value becomes the root.
- The number of nodes is in the range [0, 10^4] - -10^8 <= Node.val <= 10^8 - root is a valid BST - val does not exist in the original BST
Inserting into a BST is just search that doesn't stop early. Walk down as if looking for val; because it isn't present, you eventually fall off the tree — and that empty spot is exactly where val belongs (the invariant is preserved automatically). Attach a new leaf there. O(height).
“Where does the new value go?”
At the empty slot where a search for it would end — as a new leaf.
“Can the tree be empty?”
Yes — then the new node is the root.
I search for the value; since it isn't there, the search runs off the tree, and that null slot is where it belongs.
I create a leaf there, which keeps the BST valid without any restructuring.
Worked example — BST [4, 2, 7, 1, 3], val = 5
4 -> 5 > 4, go right
7 -> 5 < 7, go left -> null -> insert 5 as 7's left child
4
/ \
2 7
/ \ /
1 3 5
Searching for a value that isn't present lands exactly at the null slot where it belongs.
A natural insert attaches a leaf; no existing nodes move.
It's one root-to-leaf descent.
| Recursive insert | Iterative insert | |
|---|---|---|
| Idea | Recurse to the null child, return a new node | Loop to the null slot, attach a leaf |
| Time | O(height) | O(height) |
| Space | O(height) | O(1) |
Both attach the same leaf; the iterative version uses O(1) space. Full code is in the Approaches selector below.
Key takeaway
Insert = search until you fall off the tree, then attach a new leaf at that null slot. The ordering is preserved automatically. O(height) time.
descend comparing val to node at the first null child, attach new node(val)