Tree Traversals
Preorder, inorder, postorder and level order: how each one walks a binary tree, how to write them with recursion, a stack or a queue, and which order each problem needs.
Overview
A traversal visits every node of a tree exactly once. Almost every tree problem is a traversal with some work done at each node, so the real skill is choosing the order in which the nodes are visited. There are four orders worth knowing: three depth-first orders (preorder, inorder, postorder) and one breadth-first order (level order). This chapter shows all four on one small tree, then the stack, queue and thread tricks that run them, and ends with what each one costs.
Four orders, one tree
Every example in this chapter uses the same seven-node tree.
Each order follows its own rule at every node, so each one lists the same seven nodes in a different sequence.
- Preorder handles the node, then the left subtree, then the right subtree: 1, 2, 4, 5, 3, 6, 7. It is good for copying or serializing a tree, and for top-down work.
- Inorder handles the left subtree, then the node, then the right subtree: 4, 2, 5, 1, 6, 3, 7. On a binary search tree it gives the keys in sorted order.
- Postorder handles the left subtree, then the right subtree, then the node: 4, 5, 2, 6, 7, 3, 1. It is good for heights, sizes, sums and other bottom-up work.
- Level order handles one level at a time, left to right: [1], [2, 3], [4, 5, 6, 7]. It is good for anything about levels, depth or the nearest node.
Sign up free to read the full topic
More Coding & DSA topics
Start free on Cariara · Coding problems · System design studio