Loading...
Tree traversals differ in when they process a node relative to its subtrees. Keep that rule consistent at every level rather than trying to read the diagram row by row.
What you'll be able to do
For a binary tree, pre-order processes the node, then the left subtree, then the right subtree. In-order processes left subtree, node, right subtree. Post-order processes left subtree, right subtree, node. An absent subtree contributes no visit.
These are recursive rules: “left subtree” means apply the whole same traversal there, not just visit its immediate root. A small tree with one node gives the same result for all three orders, so it is insufficient to distinguish whether a rule has been applied correctly.
In-order traversal outputs keys in ascending order when the tree is a binary search tree under the stated ordering policy. An arbitrary binary tree does not become sorted simply because in-order traversal is used. The result follows from the combination of structure and algorithm.
Pre-order can record a parent before the structure below it, useful for some copying or serialisation tasks with sufficient structural information. Post-order handles children before their parent, useful for evaluating an expression tree or releasing child structures before a containing node.
Mark each recursive return point or write a small expansion for each subtree. This reduces the common error of switching from a depth-based rule to a breadth-based reading halfway through. For a proper tree, each node is processed once, giving O(V) total visits.
The call-stack depth follows the tree height, which can be logarithmic for a balanced tree or linear for a chain. A recursive implementation is concise but does not remove the need to consider an empty tree and resource limits. Distinguish the number of visits from the maximum simultaneous calls.
| Tree description | Rule result |
|---|---|
| A has children B,C; B has D,E; C has F,G | |
| Pre-order | A B D E C F G |
| In-order | D B E A F C G |
| Post-order | D E B F G C A |
Attempt the task before opening its worked response. Record each change of state, explain the rule used, and check the result against the original requirements. Code examples labelled Python 3 use that language’s conventions; pseudocode states its own assumptions.
Common mistakes to avoid
Key takeaways
Test yourself
Answer a few questions, then review anything you missed.
Start with the quiz above to check the key ideas. You can also choose another topic from the practice library.