learngraphtheory.org

Guest

Sign in to keep your graphs and progress.

Cover of the book Graph Theory Through Problems

Practice book

Graph Theory Through Problems

300 Exercises with Hints, Worked Algorithms and Complete Solutions

By Mohammed Islam Hadjoudj

Learn graph theory by solving problems: 300 exercises, from routine checks to challenging proofs, each with a complete solution.

Available inKindlePaperback

13 chapters

Also by the authorGraph Algorithms for Coding Interviews100 solved interview problems with visual explanations and Python solutions.View on Amazon
Algorithm Selection

Select an algorithm and generate steps to begin visualization

Tree Traversal Visualizer

Four ways to walk a tree

Visits every vertex of the tree rooted at the start vertex once: preorder, inorder or postorder with the call stack, or level order with a queue

Time: O(n)
Space: O(h)
Use Case: Binary search trees, expression trees, serialization
Showing the example graph for this algorithm.
Traversal order

The start vertex is the root. Children are taken left to right as drawn.

Algorithm Execution

Select an algorithm and generate steps to begin visualization

About Tree Traversal (Pre, In, Post, Level)

A tree traversal visits every vertex of a tree exactly once, in an order fixed by the shape of the tree. The three depth-first orders differ only in when a vertex is visited relative to its subtrees: preorder visits the vertex before its subtrees (root, left, right), inorder between its left and right subtree (left, root, right), and postorder after both (left, right, root). Level order, the breadth-first traversal, visits the tree one level at a time from the root down. Traversals are the first algorithms taught on binary trees and the basis of almost every recursive tree algorithm.

How it works

The depth-first orders follow one recursive walk: down into the left subtree, back up, down into the right subtree, back up. Preorder outputs a vertex on the way down, inorder between its two subtrees and postorder on the way back up. The recursion keeps the path from the root to the current vertex on the call stack, so the memory it needs is the height of the tree. Level order keeps a queue instead: take the vertex at the front, output it and add its children at the back. Every order visits each vertex once, in O(n) time. In the visualizer the start vertex is the root, children are taken left to right as drawn, and a child drawn left of its parent counts as its left child.

Applications

Preorder copies or serializes a tree and prints a file system as a directory listing. Inorder lists the keys of a binary search tree in sorted order, which is the standard way to check a BST. Postorder evaluates expression trees, adds up folder sizes and frees memory, since a node is handled only after everything below it. Level order prints a tree by levels, finds the shallowest node and is the core of breadth-first search. Traversal questions are among the most common in coding interviews.

Pseudocode

The three depth-first orders are one recursive walk with the visit placed on a different line. Level order replaces the recursion with a queue.

Preorder(v):            Inorder(v):             Postorder(v):
    visit(v)                Inorder(left(v))        Postorder(left(v))
    Preorder(left(v))       visit(v)                Postorder(right(v))
    Preorder(right(v))      Inorder(right(v))       visit(v)

LevelOrder(root):
    queue = [root]
    while queue is not empty:
        v = queue.dequeue()
        visit(v)
        queue.enqueue(left(v), right(v))

Each call does constant work besides its recursive calls and there is one call per vertex, so every order runs in O(n). The recursion is as deep as the tree is tall: about log2(n) for a balanced tree but up to n for a tree that is a single path, which is when an iterative version with an explicit stack is safer.

Worked example, step by step

Traverse the binary search tree from Wikipedia's article on tree traversal, which this page loads, with F at the root.

Example graph: F has children B (left) and G (right). B has A and D, D has C and E, G has only a right child I, and I has a left child H.

  1. Preorder. F, B, A, D, C, E, G, I, H. Each vertex comes out as soon as the walk reaches it, so the root comes first and every vertex comes before its subtree.
  2. Inorder. A, B, C, D, E, F, G, H, I. Each vertex waits for its left subtree. The letters come out in alphabetical order, which shows the tree is a binary search tree.
  3. Postorder. A, C, E, D, B, H, I, G, F. Each vertex waits for both subtrees, so the leaves come early and the root last.
  4. Level order. F, B, G, A, D, I, C, E, H. The queue hands out the tree one level at a time, left to right.
  5. The call stack. When the inorder walk visits C, the call stack holds F, B, D, C: the path from the root, which is exactly the memory the recursion needs.

The four lists hold the same nine letters in four orders. Preorder or postorder together with inorder determine a binary tree with distinct labels, so the tree could be rebuilt from two of these lists, a classic interview exercise.

Complexity, and where it comes from

Time: O(n) · Space: O(h)

Each vertex is entered and left once, and each edge is followed once down and once up, so all four traversals take O(n) time. The recursive orders keep one stack frame per vertex on the path from the root: O(h) space for a tree of height h, which is O(log n) when the tree is balanced and O(n) when it degenerates into a path. Level order holds at most one level and part of the next in its queue, O(w) for a tree of maximum width w, which reaches n/2 on a complete binary tree. Morris traversal does inorder in O(1) extra space by threading the tree temporarily.

When to use Tree Traversal (Pre, In, Post, Level), and when not to

Which order to use depends on whether a vertex needs the results of its subtrees, or they need its own.

AlternativePrefer it whenCost
PreorderHandle a node before its children: copy or serialize a tree, print a directory listing, compute depths from the root.O(n)
InorderBinary search trees: inorder gives the keys sorted, checks the BST property and finds the k-th smallest key.O(n)
PostorderA node needs its children's results first: evaluate an expression, add up folder sizes, delete a tree.O(n)
Level orderWork by distance from the root: print by levels, find the shallowest leaf, link the nodes of each level.O(n)
Morris traversalInorder or preorder without a stack or recursion when memory is tight, by threading the tree temporarily.O(n) time, O(1) space

Common pitfalls

  • Recursion that is too deep. A degenerate tree, such as sorted keys inserted into a plain BST, is a path of n vertices. Recursing on it can overflow the call stack, so long inputs need an iterative traversal with an explicit stack.
  • A single right child. A node with only a right child must be visited before that child in inorder. Code that assumes a lone child is a left child gets the order wrong, as it would at G in the example.
  • Inorder on trees that are not binary. Inorder is defined for binary trees, where a node sits between its left and its right subtree. General trees have no standard inorder, which is why this page uses the drawing to split the children into a left and a right side.
  • A stack instead of a queue. Level order needs a queue. A stack silently turns it into a depth-first order, a common bug when recursive code is rewritten as a loop.

Frequently asked questions

What is tree traversal?
Visiting every node of a tree exactly once in a systematic order. The depth-first orders are preorder, inorder and postorder, and the breadth-first order is level order.
What is the difference between preorder, inorder and postorder?
Only when a node is visited relative to its subtrees: before them in preorder (root, left, right), between them in inorder (left, root, right) and after them in postorder (left, right, root).
Why does inorder traversal of a BST give sorted output?
In a binary search tree every key in the left subtree is smaller than the node and every key in the right subtree is larger. Inorder visits the left subtree, then the node, then the right subtree, so by induction it lists the keys from smallest to largest.
Is level order traversal the same as BFS?
Yes. Level order is breadth-first search on a tree: a queue holds the nodes of the current level and their children join the back, so the nodes come out level by level.
What is the time complexity of tree traversal?
O(n) for n nodes in every order, since each node is visited once. The extra space is O(h) for the recursive orders, with h the height of the tree, and O(w) for level order, with w the largest width.

Related algorithms: Depth-First Search, Breadth-First Search, Prüfer Code, Huffman Coding

An example graph: you can change it, or start blank.

Zoom Controls

30%
Nodes: 9
Edges: 8