Kodewick
Start learning →
Four ways to walk a binary tree23 / 52

Four ways to walk a binary tree

Lesson 23 of 52 · Part 5 · Trees · about 20 minutes

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.

1
2
4
5
3
6
1void preorder(TreeNode* t) {2    if (t == nullptr) return;3    cout << t->val << ' ';     // root4    preorder(t->left);         // left5    preorder(t->right);        // right6}

Preorder: visit a node the moment you reach it (the number at its top right is its turn), then go left, and only go right when the left is finished

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.

Choose one

Write down this tree's preorder traversal.

1        A2       / \3      B   C4     / \   \5    D   E   F6           /7          G
Choose one

Write down this tree's postorder traversal.

1          A2        /   \3       B     C4        \   /5         D E6        /7       F
Fill inTap one to fill a blank; tap a blank to take it back

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}
Exercise 1

Write postorder

Finish post: left, right, and print this node last.

It should print
1 6 3 14 10 8
exercise1.cpp
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}
Output
Press Run or Ctrl+Enter

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.

*
+
3
4
5

Postorder on an expression tree: left, right, then the node itself, which reads out the postfix expression 3 4 + 5 *
main.cpp
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}
Output
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.

Guess the outputA wrong guess is fine

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}
Choose one

What is this expression tree's postorder traversal (its postfix expression)?

1      *2     / \3    3   +4       / \5      4   5
Choose one

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.)

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:

q (the nodes that have been queued)012345↑head
1TreeNode* 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}

Level order: take one node out and visit it, then put its children at the back. The order they come out is level by level, left to right
main.cpp
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}
Output
1 2 3 4 5 6 
TraversalOrderHowThis tree
Preorderroot left rightRecursion, visit first1 2 4 5 3 6
Inorderleft root rightRecursion, visit in the middle4 2 5 1 3 6
Postorderleft right rootRecursion, visit last4 5 2 6 3 1
Level orderlevel by levelA queue1 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.

Choose one

Write down this tree's level-order traversal.

1        A2       / \3      B   C4     / \   \5    D   E   F6           /7          G
Put in orderDrag, or use the arrows

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.

  1. if (x->right) q[tail++] = x->right;
  2. TreeNode* x = q[head++];
  3. if (x->left) q[tail++] = x->left;
  4. cout << x->val << " ";
Should print
1 2 3 4 5 6
Choose one

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?

Exercise 2

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.

It should print
1 2 3 1
exercise2.cpp
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}
Output
Press Run or Ctrl+Enter

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.

main.cpp
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}
Output
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).

VersionContainerExtra space
Recursive pre / in / postorderThe call stackO(height)
Non-recursive preorderstack<TreeNode*>O(height)
Level orderqueue<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.

Choose one

In the non-recursive preorder, why is the right child pushed first and the left child second?

Summary

Take-away

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}