Back to writing
Algorithm

Tree Traversal Part 1: Overview

Overview

Tree traversal means visiting every node in a tree-shaped data structure exactly once according to a specific rule. Unlike linear data structures such as lists and arrays, trees have a hierarchical structure, and a single node can have multiple child nodes. Because of that, several traversal patterns can be defined depending on the root, order, and timing of visits.

There are two major algorithms for traversing tree structures: BFS, or breadth-first search, and DFS, or depth-first search.

Tree Traversal Techniques木の走査技法の分類図。DFSとBFSの2種類に大別され、DFSはInorder・Preorder・Postorderの3種に分かれる。Tree Traversal TechniquesDepth First Traversal(DFS)Breadth First Traversal(Level Order Traversalor BFS)Inorder TraversalPreorder TraversalPostorder Traversal

BFS (Breadth-First Search)

BFS uses a queue and visits all nodes at the same depth before moving to the next depth.

Visit order: A -> B -> C -> D -> E -> F -> G

It is well suited for problems that require the shortest path, such as maze solving.

DFS (Depth-First Search)

DFS uses a stack, or recursion, and follows a path as deeply as possible before backtracking. There are three common visit timings.

  • Pre-order: self -> left -> right
  • In-order: left -> self -> right, often used to output a binary search tree in ascending order
  • Post-order: left -> right -> self, useful for tasks such as aggregating file sizes
Tree Traversal Orders: Pre-Order, In-Order, Post-OrderComparison of three binary tree traversal methods with animated diagrams and pseudocode.Pre-Orderroot → left → rightRLRfunction pre-order(T)if !ISEMPTY(T) then① visit(root(T))pre-order(left(T))pre-order(right(T))end if / end functionIn-Orderleft → root → rightLRRfunction in-order(T)if !ISEMPTY(T) thenin-order(left(T))② visit(root(T))in-order(right(T))end if / end functionPost-Orderleft → right → rootLRRfunction post-order(T)if !ISEMPTY(T) thenpost-order(left(T))post-order(right(T))③ visit(root(T))end if / end functionTraversal order comparison on the same treeRoot nodeLeft subtreeRight subtreevisit( ) callExample: root = A, left = B, right = CMethodVisit orderCommon use casePre-OrderA → B → CTree copy / serializationIn-OrderB → A → CSorted output from BSTPost-OrderB → C → AMemory free / dependency resolve

Complexity

If V is the number of nodes, E is the number of edges, and H is the height of the tree, both BFS and DFS have a time complexity of O(V + E). Their space complexity differs: BFS is O(V), while DFS is O(H).

AlgorithmTime ComplexitySpace Complexity
BFSO(V + E)O(V)
DFSO(V + E)O(H), where H is the height of the tree

Interactive Demo

Choose an algorithm and press the "Next" button to see the order in which nodes are visited step by step.

ABCDEFG
「次へ」で開始