How to recognise
a tree problem where the order you meet the nodes matters: sorted values or the k-th smallest in a BST (in-order), copying or saving a tree (pre-order), sizes, heights and deleting (post-order).
How to solve problems like this
- Pick the order by when a node needs its work done: before its children (pre), between them (in) or after them (post).
- Write f(node). If node is none, return.
- Put the node's own work before, between or after the calls f(node.left) and f(node.right).
- In a BST, in-order gives the values sorted: use it for the k-th smallest, to check that a tree is a BST, or to compare neighbours.
Where it's used
- Deleting a folder. rm -r cannot delete a folder while something is in it, so it deletes the contents first and the folder after. That is post-order.
- Web pages. document.querySelectorAll returns elements in document order: an element, then its children in turn. That is a pre-order walk of the HTML tree.
- Compilers. To work out (2 + 3) × 4 you need both operands before the operation, so the expression tree is walked in post-order. Python bytecode looks just like that: load the operands, then the operation.