Builds onTree basics
01The idea
To traverse a tree is to visit every node once. There are two families of traversal.
Depth-first traversal goes as deep as it can before it backs up. It is written as a recursive function, and the only question is when you handle the node itself:
- Preorder handles the node, then the left subtree, then the right subtree. It handles a parent before its children.
- Inorder handles the left subtree, then the node, then the right subtree. On a binary search tree it visits the values in sorted order.
- Postorder handles the left subtree, then the right subtree, then the node. It has the children's answers before it handles the parent, which suits "compute from the bottom up".
Breadth-first traversal, also called level order, visits the tree one level at a time. It uses a queue. Take a node from the front, handle it, and put its children at the back. Because the queue returns nodes in arrival order, every node of one level comes out before any node of the next.
To know where a level ends, read len(queue) at the start of the level. At that moment the queue holds exactly that level. Take that many nodes, and the children they add wait for the next round.
02How to spot it
Choose the traversal from the question:
- The answer for a node needs the answers for its children, such as heights, sizes or sums of subtrees. Use postorder.
- Each node needs information from its ancestors, such as the path from the root or a running maximum. Use preorder, and pass the information down as an argument.
- The tree is a binary search tree and order matters. Use inorder.
- The question mentions levels, depth, rows, "left side" or "right side" views, or the nearest node to the root. Use level order with a queue.
Both families take O(n) time. They differ in the order of visits and in memory. Depth-first uses stack space for the height of the tree. Level order uses queue space for the widest level.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue