Traversal of a Binary-Tree

In this blog post we will investigate four key algorithms used to read through the content of a binary tree:

  • Breadth-First Traversal Algorithm
  • Depth-First Algorithms:
    • Pre-Order Traversal
    • In-Order Traversal
    • Post-Order Traversal

Binary Tree?


A Binary Tree is a data structure used in some algorithms to store data. In a binary tree each node can have up to two children.
Binary-Search-Tree

Breadth-First Traversal Algorithm


A Breadth-first traversal consists of accessing each node, one level after the other. On each layer the nodes are accessed as they appear, from left to right.
breadth-first-traversal

Depth-First Traversal Algorithms


There are three depth-first traversal agorithms which are all based on a recursive approach.
depth-first-traversal

Pre-Order Traversal Algorithm:

FUNCTION preorder-traverse(tree)
    IF tree is not empty
         visit root node of tree
         preorder-traverse(left sub-tree)
         preorder-traverse(right sub-tree)
    END IF
END FUNCTION 

In-Order Traversal Algorithm:

FUNCTION inorder-traverse(tree)
    IF tree is not empty
         inorder-traverse(left sub-tree)
         visit root node of tree
         inorder-traverse(right sub-tree)
    END IF
END FUNCTION 

Post-Order Traversal Algorithm:

FUNCTION postorder-traverse(tree)
    IF tree is not empty
         postorder-traverse(left sub-tree)
         postorder-traverse(right sub-tree)
         visit root node of tree
    END IF
END FUNCTION 

Binary Tree #1

Binary-tree-traversal-3
Breadth First: (view solution)
Depth-first Pre-order Traversal: (view solution)
Depth-first In-order Traversal: (view solution)
Depth-first Post-order Traversal: (view solution)

Binary Tree #2

Breadth First: (view solution)
Depth-first Pre-order Traversal: (view solution)
Depth-first In-order Traversal: (view solution)
Depth-first Post-order Traversal: (view solution)

Binary Tree #3

Binary-Search-Tree-2
Breadth First: (view solution)
Depth-first Pre-order Traversal: (view solution)
Depth-first In-order Traversal: (view solution)
Depth-first Post-order Traversal: (view solution)

Binary Tree #4

Binary-Search-Tree-1
Breadth First: (view solution)
Depth-first Pre-order Traversal: (view solution)
Depth-first In-order Traversal: (view solution)
Depth-first Post-order Traversal: (view solution)

Did you like this challenge?

Click on a star to rate it!

Average rating 4.4 / 5. Vote count: 50

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!

Tagged with: