Data Structures · Visualization
BST: Insert
Binary Search Tree
Inserting into a BST means finding the correct empty spot according to the ordering rule (smaller goes left, larger goes right) and placing the new node there. Time: O(h), O(log n) average, O(n) worst case. Space: O(h) recursive, O(1) iterative.
Big-O: Search/insert/delete O(log n) on a balanced tree, O(n) worst case.
BST: Insert
Binary Search TreeInserting into a BST means finding the correct empty spot according to the ordering rule (smaller goes left, larger goes right) and placing the new node there. You compare the new value against each node starting from the root, moving left or right, until you find an empty spot to attach it.
How Insert Works
- Start at the root.
- If the tree is empty, the new value becomes the root and you're done.
- Compare the new value with the current node: if smaller, move left; if larger, move right.
- Repeat until you reach an empty (null) spot.
- Attach the new node there.
Insert Worked Example
Input: Insert 5 into a BST with root 8, left child 3
- Compare 5 with root(8): 5 < 8, go left
- Compare 5 with node(3): 5 > 3, go right
- Node(3)'s right child is empty — attach 5 there
Output: 8 / 3 \ 5
Press ▶ Run to watch it step by step.
def insert(root, val):
if not root:
return Node(val)
if val < root.val:
root.left = insert(root.left, val)
else:
root.right = insert(root.right, val)
return root
# O(log n) on a balanced tree
# example: insert 5Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Insert Time & Space Complexity
When to Use Insert
- Building a searchable, sorted structure from a stream of incoming values
- Maintaining leaderboard or ranking data with fast updates
- Any application needing sorted-order insertion without full re-sorting
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.