Inserting into a BST

Walk down like a search, attach like a leaf, keeping the BST ordering promise intact.

Inserting into a BST is searching for a spot that doesn't exist yet. Compare the new value at each node, smaller goes left, bigger goes right, until you hit an empty position. That's the new node's home.

Because the walk follows the same ordering rule as search, the promise (smaller-left, bigger-right) survives automatically. On a balanced tree the walk is O(log n), the same halving that makes lookup fast makes insertion fast too.

Remember this

  • Insert = search until you fall off the tree, attach there
  • The ordering promise is preserved by construction
  • O(log n) on a balanced tree

Got a different question? SeaThru generates a fresh video for any topic where systems talk or data structures move.

Ask your own question →

Keep learning