Inserting into a BST
Insertion follows a simple rule: find where the value should go, then add it there. The BST property tells us exactly where.
The Algorithm
Here’s the process:
- Start at the root
- Compare value with current node
- If smaller, go left; if larger, go right
- If you reach null, that’s where it goes
- Create a new node there
Recursive Implementation
Recursion fits this problem well. Here’s how:
🟨 JavaScript BST Insertion (Recursive)
📟 Console Output
Run code to see output...
Iterative Implementation
Some prefer iteration. Here’s the same logic without recursion:
🟨 JavaScript BST Insertion (Iterative)
📟 Console Output
Run code to see output...
Try It Yourself
Use the interactive BST builder to insert values:
Ready
Try inserting: 50, 30, 70, 20, 40, 60, 80. Watch how each value finds its correct position.
Step-by-Step Example
Let’s insert 35 into this tree:
50
/ \
30 70
/ \ / \
20 40 60 80
- Start at 50. 35 < 50, go left
- At 30. 35 > 30, go right
- At 40. 35 < 40, go left
- Found null! Insert 35 here
Result:
50
/ \
30 70
/ \ / \
20 40 60 80
\
35
Time Complexity
- Average case: O(log n) - we traverse one path from root to leaf
- Worst case: O(n) - if tree is unbalanced (like a linked list)
The average case is what makes BSTs useful. Most real-world trees stay reasonably balanced.
Common Mistakes
- Forgetting to return the new node: In recursion, you must return the node
- Not handling null root: Empty tree needs special handling
- Breaking BST property: Always compare and go left/right correctly
- Duplicate values: Decide whether to allow duplicates or ignore them
What’s Next?
Now that you can insert nodes, let’s learn how to search for values. It’s similar to insertion but simpler.
Progress 43%
Page 3 of 7
← Previous
→ Next