Go down one branch to the bottom before trying the next.
O(N) time · O(H) spaceVisualize hierarchical structures and traversals: Pre, In, Post, and Level order.
2 algorithms6 variants1 race7 problems
2 algorithms. Each one builds on the last.
Go down one branch to the bottom before trying the next.
O(N) time · O(H) spaceVisit the tree level by level with a queue.
O(N) time · O(N) spaceSame input, side by side. Watch who wins.
These pages walk a binary tree, where each node has at most two children and no rule decides which values go where. Each page answers a question by visiting the nodes in a planned order. Tree questions are an interview staple, and the same walks run inside file browsers, HTML parsers and compilers.
Every page visits each node at most once, so none costs more than O(N) time. They differ in order. A queue gives level order, one whole level at a time; recursion follows one branch to the bottom before the next, handling the node before, between or after its subtrees.
If the question mentions levels or the nearest leaf, use a queue. If a node needs a value from above, such as a running sum, handle it before its children; if it needs one from below, such as a height, handle it after them. A common slip is expecting in-order output to be sorted on any tree: that holds only for a search tree.