Tree Algorithms

Level-Order Traversal (Breadth-First on a Tree)

40241136554859
Output so far

Nothing yet.

  • Not reached
  • On the stack
  • Current
  • Visited
1/13

Level-Order walk over 7 values, 3 levels deep.

Settings

More options
How it was built

Level-Order

  1. 1queue = [root]
  2. 2while queue:
  3. 3 node = queue.shift()
  4. 4 visit(node)
  5. 5 enqueue node.left
  6. 6 enqueue 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)

Scroll the table sideways for the rest of the columns.

n is the number of values, h the height of the tree and w its widest level. Built from sorted values, the tree gets a height of n. Balanced trees exist to prevent that.