← Traversals · guided lesson
Tree Traversals
the story
Binary tree
Every tool here exists because something was too slow or broke without it. Here is what.
In 1857 the mathematician Arthur Cayley published "On the theory of the analytical forms called trees" in the Philosophical Magazine.
He was counting rooted, branching shapes while studying how calculus operators combine — and the name tree stuck.
In programs, a node holding two links (left, right) became a standard building block of early list-processing and compilers; no one person is credited with it.
Today every node in a Java TreeMap is built on it: a key and a value, left and right child references (plus a parent link and a red/black colour bit).
the problem it solved
Representing hierarchy and branching — anything where one thing splits into at most two smaller things of the same kind.
why it matters: without it
Hierarchies would be flattened into lists: every "find", "insert in order" or "evaluate this expression" becomes a linear scan.
sources: Cayley — On the theory of the analytical forms called trees (Philosophical Magazine, 1857) ↗ · Knuth — The Art of Computer Programming, Vol. 1: Fundamental Algorithms (§2.3 Trees) ↗
also in this chapter: Depth-first traversal (pre, in, post order) · Breadth-first traversal (level order) · Serialization with null markers
the idea
The idea in 30 seconds
A binary tree is a node with a value and at most two children — and each child is itself a binary tree.
A traversal visits every node once. Depth-first (pre, in, post order) goes deep using a stack; breadth-first (level order) goes level by level using a queue.
Many tree problems are just the right visiting order plus one line of work at each visit.
picture this
Your File Explorer folder tree, walked two ways. Depth-first: open Projects and everything inside it before you touch Downloads — that's how the Windows tree command prints folders (preorder). Breadth-first: list every top-level folder, then every folder one level down — so the first match you find is the shallowest one.
watch it
Preorder · inorder · postorder walk
Predict mode is on. Before each step, guess what happens, then watch. Wrong guesses are fine; that is how it sinks in.
Preorder · inorder · postorder walk
Type pre, in or post. The call stack (right) is the path from the root to the current node; the output fills in when the node is *visited*.
On this screen ← / → step the simulation. Use the buttons below to move through the lesson.
watch it
Inorder without recursion
Predict mode is on. Before each step, guess what happens, then watch. Wrong guesses are fine; that is how it sinks in.
Inorder without recursion
An explicit stack does exactly what the call stack did: remember the nodes we still have to come back to.
On this screen ← / → step the simulation. Use the buttons below to move through the lesson.
key idea 1 of 8
Read it once. Say it out loud once. Bas.
Terminology: root (top, no parent), leaf (no children), edge (parent→child link). Depth = edges from the root down to a node. Height = edges on the longest path from a node down to a leaf. A tree's height is its root's height.
key idea 2 of 8
Read it once. Say it out loud once. Bas.
Shapes: full = every node has 0 or 2 children. Complete = every level full except maybe the last, filled left to right (heaps). Perfect = all levels full (2^(h+1) − 1 nodes). Balanced = at every node the two subtree heights differ by at most 1, so h = O(log n).
key idea 3 of 8
Read it once. Say it out loud once. Bas.
*DFS orders differ only in when you touch the node:* preorder = before the children (copy, serialize), inorder = between them (sorted order in a BST), postorder = after them (heights, sizes, deleting).
key idea 4 of 8
Read it once. Say it out loud once. Bas.
Iterative DFS: an ArrayDeque does the call stack's job. Inorder loop: dive left pushing every node, pop one, visit it, go right. Postorder trick: a root → right → left preorder, reversed.
key idea 5 of 8
Read it once. Say it out loud once. Bas.
BFS uses a queue. Snapshot size = queue.size() at the start of each round to process exactly one level — the trick behind every "level" problem.
key idea 6 of 8
Read it once. Say it out loud once. Bas.
Space: DFS holds one root-to-node path → O(h). BFS holds about one level → O(w), the widest level. A perfect tree is short and wide (DFS wins); a skewed chain is tall and thin (BFS wins).
key idea 7 of 8
Read it once. Say it out loud once. Bas.
*When the order is the answer:* level lists, zigzag, right side view, averages, next pointers and serialization are all "traverse in the right order, do one line of work per node".
key idea 8 of 8
Read it once. Say it out loud once. Bas.
A tree is a graph that only points down. Record each node's parent in a HashMap and you can walk up too — then a BFS from any node measures distances (All Nodes Distance K).
spot the pattern
When you see this, think this
"Level", "row", "zigzag", "right side view", "average of each level"
BFS with
size = queue.size()per round"Can you do it without recursion?"
Explicit
ArrayDequestack — inorder: dive left, pop, visit, go rightValues of a BST in sorted order, k-th smallest
Inorder traversal
"Copy", "serialize", "encode" a tree
Preorder (or BFS) with a marker for every null
+4 more signals on the chapter page
watch out
A trap or two
Many wrong answers in interviews come from small slips like these, not from the hard part.
- Offering
nullchildren to anArrayDeque— it throws. Checkif (node.left != null)first. - Using
queue.size()directly in theforcondition: it changes while you offer children. Store it in a variable first.
quick check
One question. No pressure.
Preorder of the tree root 1, left child 2 (with children 4 and 5), right child 3?
now try
Your first real problem
You know enough to try this one. Stuck? Use the hints; that is what they are for.
Binary Tree Inorder Traversal
open the problem →recall
Flip a few cards
Answer in your head first, then flip. Grade yourself honestly; the schedule brings back what you forget.
Preorder, inorder, postorder: where does the "visit" line go in each?
Question 1: Preorder, inorder, postorder: where does the "visit" line go in each?
done
Lesson complete
Chalo, that is the core. The full chapter has the rest: cost tables, Java details and more problems.