0

BST Insert & Search

Medium

Left is smaller, right is larger. That one rule turns search, insert and delete into a single walk down the tree.

ordering invariantlogarithmic
TimeO(h), which is O(log n) when balanced
SpaceO(1) iterative
Inputvalues to insert | value to search
50

50 becomes the root.

1 / 21
insert(node, v):
if node is null: return new Node(v)
if v < node.val: node.left = insert(node.left, v)
else: node.right = insert(node.right, v)
search(node, v): same walk, compare and descend
Why it matters

Inserting sorted data degrades the tree into a linked list. That is why self-balancing trees exist.

Keyboard
space play← → stepr restartctrl K search

More in Binary Search Tree

Next visualiser
Validate a BST