Four ways to walk a binary tree
Binary tree traversal visits each node once in preorder (root, left, right), inorder (left, root, right), postorder (left, right, root) or level order with a std::queue; on an expression tree the first three give prefix, infix and postfix.
An array is walked from front to back, and there is only one order. A tree is different: at a node, do you deal with the node first, or go left first, then right? Different orders give completely different sequences, and nearly every year the exam hands you a tree and asks for one of its traversal sequences.
Preorder, inorder, postorder: only where "this node" goes
All three recursive traversals do "the left subtree, then the right subtree"; the only difference is when the root is visited:
- Preorder (root, left, right): visit this node first, then left, then right.
- Inorder (left, root, right): left first, then visit this node, then right.
- Postorder (left, right, root): left, then right, and this node last.
Inorder and postorder just move the cout line between the two recursive calls, or after them.
1void preorder(TreeNode* t) {2 if (t == nullptr) return;3 cout << t->val << ' '; // root4 preorder(t->left); // left5 preorder(t->right); // right6}
The other two for the same tree: inorder 4 2 5 1 3 6 (every node after its left subtree and before its right), postorder 4 5 2 6 3 1 (the root always last). The last lesson's destroy is a postorder traversal: only once both children are deleted is it this node's turn.
Write down this tree's preorder traversal.
1 A2 / \3 B C4 / \ \5 D E F6 /7 G
Write down this tree's postorder traversal.
1 A2 / \3 B C4 \ /5 D E6 /7 F
Fill in the two blanks so in becomes an inorder traversal: left, then the node itself, then right. The tree is the one from the first picture, so the program should print 4 2 5 1 3 6.
1#include <iostream>2using namespace std;3 4struct TreeNode {5 int val;6 TreeNode *left, *right;7 TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)8 : val(v), left(l), right(r) {}9};10 11void in(TreeNode* t) {12 if (t == nullptr) return;13 ;14 cout << t->val << " ";15 ;16}17 18int main() {19 TreeNode* t = new TreeNode(1, new TreeNode(2, new TreeNode(4), new TreeNode(5)),20 new TreeNode(3, nullptr, new TreeNode(6)));21 in(t);22 cout << "\n";23 return 0;24}
cout sits between the two recursive calls, with the left one before it and the right one after. Swap the blanks and you get right, root, left: 6 3 1 5 2 4.Write postorder
✓Finish post: left, right, and print this node last.
1 6 3 14 10 8
1#include <iostream>2using namespace std;3 4struct TreeNode {5 int val;6 TreeNode *left, *right;7 TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)8 : val(v), left(l), right(r) {}9};10 11void post(TreeNode* t) {12 // return straight away for an empty tree; otherwise left, then right, then cout << t->val << ' '13}14 15int main() {16 TreeNode* t = new TreeNode(8, new TreeNode(3, new TreeNode(1), new TreeNode(6)),17 new TreeNode(10, nullptr, new TreeNode(14)));18 post(t);19 cout << endl;20 return 0;21}
Expression trees: three traversals, three notations
The expression (3 + 4) * 5 can be stored as a tree: operators in the inner nodes, numbers in the leaves. Its three traversals give exactly the prefix, infix and postfix expressions, and postfix is the one chapter 2 evaluated with a stack. The nodes in this section hold characters, so val is a char.
1#include <iostream>2using namespace std;3 4struct TreeNode {5 char val;6 TreeNode *left, *right;7 TreeNode(char v, TreeNode* l = nullptr, TreeNode* r = nullptr)8 : val(v), left(l), right(r) {}9};10 11void pre(TreeNode* t) {12 if (!t) return;13 cout << t->val << ' ';14 pre(t->left);15 pre(t->right);16}17 18void in(TreeNode* t) {19 if (!t) return;20 in(t->left);21 cout << t->val << ' ';22 in(t->right);23}24 25void post(TreeNode* t) {26 if (!t) return;27 post(t->left);28 post(t->right);29 cout << t->val << ' ';30}31 32int main() {33 // (3 + 4) * 534 TreeNode* t = new TreeNode('*', new TreeNode('+', new TreeNode('3'), new TreeNode('4')),35 new TreeNode('5'));36 cout << "preorder: ";37 pre(t);38 cout << "\ninorder: ";39 in(t);40 cout << "\npostorder: ";41 post(t);42 cout << endl;43 return 0;44}
preorder: * + 3 4 5 inorder: 3 + 4 * 5 postorder: 3 4 + 5 *
Notice that inorder prints 3 + 4 * 5: the brackets are lost, and by the usual rules 4 * 5 is done first, which changes the meaning. Infix needs brackets, while prefix and postfix are never ambiguous without them; that is why computers like postfix.
What does an inorder traversal of this tree print (B has only a left child, D)?
1#include <iostream>2using namespace std;3 4struct TreeNode {5 char val;6 TreeNode *left, *right;7 TreeNode(char v, TreeNode* l = nullptr, TreeNode* r = nullptr)8 : val(v), left(l), right(r) {}9};10 11void in(TreeNode* t) {12 if (!t) return;13 in(t->left);14 cout << t->val;15 in(t->right);16}17 18int main() {19 // A20 // B C21 // D E F22 TreeNode* t = new TreeNode('A', new TreeNode('B', new TreeNode('D')),23 new TreeNode('C', new TreeNode('E'), new TreeNode('F')));24 in(t);25 cout << endl;26 return 0;27}
What is this expression tree's postorder traversal (its postfix expression)?
1 *2 / \3 3 +4 / \5 4 5
* 3 + 4 5 is preorder (prefix), and 3 * 4 + 5 is inorder, which without brackets means (3 × 4) + 5. 3 4 + 5 * is the tree for (3 + 4) × 5.What is the value of the postfix expression 2 3 4 * +? (Read left to right: numbers are pushed; an operator pops two numbers and pushes the result.)
* pops 4 and 3 and pushes 12; + pops 12 and 2 and pushes 14. Its expression tree has + at the root, 2 on the left and 3 * 4 on the right: 2 + 3 × 4 in infix.Level order: one level at a time, with a queue
Level order starts at the root and visits one level at a time, left to right within each level. It isn't recursive; it uses a queue: the root goes in first; each time, take one node out, visit it, and put its left and right children in (if they aren't empty). First in, first handled, so an upper level always comes out before the level below. First, a queue written by hand with an array and two indexes:
head1TreeNode* q[100];2int head = 0, tail = 0;3q[tail++] = t;4while (head < tail) {5 TreeNode* x = q[head++];6 cout << x->val << ' ';7 if (x->left) q[tail++] = x->left;8 if (x->right) q[tail++] = x->right;9}
1#include <iostream>2using namespace std;3 4struct TreeNode {5 int val;6 TreeNode *left, *right;7 TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)8 : val(v), left(l), right(r) {}9};10 11void level(TreeNode* t) {12 TreeNode* q[100];13 int head = 0, tail = 0;14 if (t) q[tail++] = t;15 while (head < tail) {16 TreeNode* x = q[head++]; // dequeue17 cout << x->val << ' ';18 if (x->left) q[tail++] = x->left; // enqueue the children19 if (x->right) q[tail++] = x->right;20 }21 cout << endl;22}23 24void destroy(TreeNode* t) { // postorder: children first, then this node25 if (!t) return;26 destroy(t->left);27 destroy(t->right);28 delete t;29}30 31int main() {32 TreeNode* t = new TreeNode(1, new TreeNode(2, new TreeNode(4), new TreeNode(5)),33 new TreeNode(3, nullptr, new TreeNode(6)));34 level(t);35 destroy(t);36 return 0;37}
1 2 3 4 5 6
| Traversal | Order | How | This tree |
|---|---|---|---|
| Preorder | root left right | Recursion, visit first | 1 2 4 5 3 6 |
| Inorder | left root right | Recursion, visit in the middle | 4 2 5 1 3 6 |
| Postorder | left right root | Recursion, visit last | 4 5 2 6 3 1 |
| Level order | level by level | A queue | 1 2 3 4 5 6 |
All four visit each node once: O(n). The three recursive ones use the call stack, as deep as the tree is tall; level order uses the queue, which holds at most one level's nodes at a time.
In exams: A quick way to write preorder by hand: start at the root and go round the outside of the tree anticlockwise, writing a node down the first time you pass it; for inorder write it when you pass underneath it, and for postorder the last time you pass it. The last node of a postorder and the first of a preorder is always the root.
Write down this tree's level-order traversal.
1 A2 / \3 B C4 / \ \5 D E F6 /7 G
Put the four lines inside the while in order so the level-order walk prints 1 2 3 4 5 6. The tree is the one from the first picture.
if (x->right) q[tail++] = x->right;TreeNode* x = q[head++];if (x->left) q[tail++] = x->left;cout << x->val << " ";
1 2 3 4 5 6
x off the queue before you can visit it or queue its children; the left child has to join before the right one, so each level comes out left to right. Visiting before or after queueing the children doesn't matter: the output is the same.This step's queue walks a full binary tree with 4 levels (15 nodes) in level order. What is the most nodes the queue holds at once?
How many nodes on each level
✓Do a level order with a queue and print how many nodes each level has. The trick: at the start of each round the queue holds exactly one whole level, so note q.size() first.
1 2 3 1
1#include <iostream>2#include <queue>3using namespace std;4 5struct TreeNode {6 int val;7 TreeNode *left, *right;8 TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)9 : val(v), left(l), right(r) {}10};11 12void widths(TreeNode* root) {13 queue<TreeNode*> q;14 q.push(root);15 while (!q.empty()) {16 int k = q.size(); // this level has k nodes17 cout << k << ' ';18 // take all k out, and put their children in19 }20 cout << endl;21}22 23int main() {24 TreeNode* t = new TreeNode(1, new TreeNode(2, new TreeNode(4), new TreeNode(5)),25 new TreeNode(3, nullptr, new TreeNode(6, new TreeNode(7))));26 widths(t);27 return 0;28}
With the STL
The array queue we wrote for level order has to guess a size (100), and a bigger tree runs off its end. std::queue grows by itself, so level order just uses it. Preorder can go without recursion too: a std::stack stands in for the call stack; pop one and visit it, then push the right child first and the left child second, so the left comes out first.
1#include <iostream>2#include <queue>3#include <stack>4using namespace std;5 6struct TreeNode {7 int val;8 TreeNode *left, *right;9 TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)10 : val(v), left(l), right(r) {}11};12 13void level(TreeNode* root) {14 queue<TreeNode*> q;15 if (root) q.push(root);16 while (!q.empty()) {17 TreeNode* x = q.front();18 q.pop();19 cout << x->val << ' ';20 if (x->left) q.push(x->left);21 if (x->right) q.push(x->right);22 }23 cout << endl;24}25 26void preorder(TreeNode* root) {27 stack<TreeNode*> s;28 if (root) s.push(root);29 while (!s.empty()) {30 TreeNode* x = s.top();31 s.pop();32 cout << x->val << ' ';33 if (x->right) s.push(x->right); // the right goes in first34 if (x->left) s.push(x->left); // the left goes in second, comes out first35 }36 cout << endl;37}38 39int main() {40 TreeNode* t = new TreeNode(1, new TreeNode(2, new TreeNode(4), new TreeNode(5)),41 new TreeNode(3, nullptr, new TreeNode(6)));42 cout << "level order: ";43 level(t);44 cout << "preorder: ";45 preorder(t);46 return 0;47}
level order: 1 2 3 4 5 6 preorder: 1 2 4 5 3 6
queue and stack are both a thin layer over a deque by default (a deque is an array in blocks), and push, pop, front and top are all O(1).
| Version | Container | Extra space |
|---|---|---|
| Recursive pre / in / postorder | The call stack | O(height) |
| Non-recursive preorder | stack<TreeNode*> | O(height) |
| Level order | queue<TreeNode*> | O(widest level) |
The non-recursive version is as fast as the recursive one; the gain is that its depth is limited only by memory: a chain a hundred thousand levels deep can overflow the call stack, but not your own stack.
In interviews: "Print it level by level, one line per level" (LeetCode 102) is a variation on level order: at the start of each round, note q.size(), which is exactly that level's count. "Write inorder without recursion" comes up often too: push left children all the way down, and when you hit empty, pop one, visit it and move to its right.
In the non-recursive preorder, why is the right child pushed first and the left child second?
Summary
Four traversals: where the root goes, or level by level
- Preorder root-left-right, inorder left-root-right, postorder left-right-root: only where the cout goes
- Expression trees: preorder = prefix, inorder = infix (needs brackets), postorder = postfix
- Level order: a queue, take one out, put its children in; non-recursive preorder: a stack, right pushed first
- All O(n); the first of a preorder and the last of a postorder is the root
1void in(TreeNode* t) {2 if (!t) return;3 in(t->left);4 cout << t->val << ' ';5 in(t->right);6}