Binary Tree Traversal

Data Structures and Algorithms Note

Allie Hsu
Coder Life
3 min readJan 29, 2022

--

Breadth-First /Level Order Traversal: 1 2 3 4 5
Depth First Traversals:
> Preorder (Root, Left, Right) : 1 2 4 5 3
> Inorder (Left, Root, Right) : 4 2 5 1 3
> Postorder (Left, Right, Root) : 4 5 2 3 1

Unlike linear data structures can be traversed in only one way, trees can be traversed in various ways, especially these two ways:

1. Breadth First Traversal (BFT)/ Level Order Traversal

go to the specific level by keep go node.left/node.right until the level is 1(as if the root is one)

In order to get the maximum width of the tree, use queue:

— — —-----
-> 4 3 2 1 ->
—------— —

2. Depth First Traversal (DFT)

  • Preorder Traversal (Root L R)
  • Inorder Traversal (L Root R)

using stack

  • Postorder Traversal (L Root R)

How to choose

BFS starts visiting nodes from the root while DFS starts visiting nodes from leaves. So if the problem is to search the node that is closer to the root, then use BFS. And if the target node is close to a leaf, we would prefer DFS.

--

--

Allie Hsu
Coder Life

A tech enthusiast who is keen to develop new skills