Insert into a Binary Search Tree
Pattern: Search, insert and delete
Walk down as in a search until the spot where the value would be, an empty child, and attach a new node there. Every value already in the tree keeps its place.
The problem
Insert val (not already in the tree) into the BST and return the root. Several trees are correct, so the tests print the result's inorder and check that it is a valid BST. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.
Think first
- Where would a search for
valend? - Is it always safe to put the new node there?
- What about an empty tree?
Hints
Brute force, and why it fails
Collect all values, add the new one and rebuild a BST: O(n).
The key insight
The empty spot a search ends at is a valid place for the value, so insertion is a search plus one link.
Dry run
| at | 7 |
|---|
root = [4, 2, 7, 1, 3], val = 5. 5 > 4: go right to 7.
Step 1 of 3
The plan
if root is null: return node(val)
walk down; at the first empty child on the correct side, attach node(val)
return root
Complexity
- Time
O(h)- Space
O(1)
One path down.
Edge cases
- Empty tree.
- A value smaller than everything.
- A value larger than everything.
I've built my logic, show the code
Java
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) return new TreeNode(val); // an empty spot: the new value goes here
TreeNode n = root;
while (true) {
if (val < n.val) {
if (n.left == null) { n.left = new TreeNode(val); break; }
n = n.left;
} else {
if (n.right == null) { n.right = new TreeNode(val); break; }
n = n.right;
}
}
return root;
}
}C++
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if (root == NULL) return new TreeNode(val); // an empty spot: the new value goes here
TreeNode* n = root;
while (true) {
if (val < n->val) {
if (n->left == NULL) { n->left = new TreeNode(val); break; }
n = n->left;
} else {
if (n->right == NULL) { n->right = new TreeNode(val); break; }
n = n->right;
}
}
return root;
}
};Python
from lib import TreeNode
class Solution:
def insertIntoBST(self, root, val: int):
if root is None:
return TreeNode(val) # an empty spot: the new value goes here
n = root
while True:
side = "left" if val < n.val else "right"
child = getattr(n, side)
if child is None:
setattr(n, side, TreeNode(val))
return root
n = childCommon mistakes
- Inserting at the root and shifting nodes.
- Forgetting to return the new root when the tree was empty.