BST Insert & Search visualization

Insert values into a binary search tree, then search for a key by walking left or right.

Every node keeps smaller keys in its left subtree and larger keys in its right. Insert and search both follow a single root-to-leaf path, so they cost O(height).

Edge cases: duplicates are ignored here (a policy choice); inserting sorted input produces a degenerate, list-shaped tree where height = n and operations become O(n).

Complexity

Time: best O(log n), average O(log n), worst O(n). Space: O(n). Difficulty: Beginner.

Pseudocode

procedure insert(root, x):
  if root is null: return new node(x)
  if x = root.key: return root          // duplicate ignored
  if x < root.key: root.left ← insert(root.left, x)
  else: root.right ← insert(root.right, x)
procedure search(root, k):
  while root ≠ null and root.key ≠ k:
    root ← k < root.key ? root.left : root.right
  return root (null = not found)

More trees algorithms