Tree Algorithms

A binary search tree you can rebuild at will. Walk it in four different orders or search it for a value, and see what happens to the height when the inserts arrive already sorted.

40241136554859
Output so far

Nothing yet.

  • Not reached
  • On the stack
  • Current
  • Visited
Speed

Step 1 of 19

In-order walk over 7 values, 3 levels deep.

Counters

Visited
0/7
On the stack
0
Tree height
3
Nodes
7

Settings

Walk
How it was built

In-order

  1. 1stack = []; node = root
  2. 2while node or stack:
  3. 3 while node:
  4. 4 stack.push(node)
  5. 5 node = node.left
  6. 6 node = stack.pop()
  7. 7 visit(node)
  8. 8 node = node.right

What each walk is for

WalkWhat you getTimeExtra space
In-orderValues in sorted orderO(n)O(h)
Pre-orderRoot before children, for copying a treeO(n)O(h)
Post-orderChildren before root, for freeing or evaluatingO(n)O(h)
Level-orderShallowest nodes first, level by levelO(n)O(w)
SearchOne value, by comparing at each nodeO(h)O(1)

h is the tree height and w its widest level. Build the same values with Sorted inserts and h becomes n, which is what balancing exists to prevent.