How binary search tree insertion works
To insert, start at the root and compare: smaller goes left, larger goes right, until you reach an empty child, where the new node is attached. The recursive version returns the subtree’s root at every level, so each parent re-links its child on the way back up.
The Python example inserts 50, 30, 70, 20, 40, 60, 80, which produces a perfectly balanced tree three levels deep.
What to watch for when it runs
- The path each value takes down from the root is highlighted as it descends.
- New nodes only ever appear as leaves — insertion never rearranges existing nodes.
- Insert the same values in sorted order and the tree degenerates into a chain, making every operation O(n).
Time and space complexity
- Time
- O(h) per insert — O(log n) balanced, O(n) worst case
- Space
- O(h) recursion
h is the height of the tree. Self-balancing trees (AVL, red-black) exist to keep h at O(log n) whatever order values arrive in.