Breadth-First Search and Depth-First Search are two techniques of traversing graphs and trees. In this tutorial, we will focus mainly on BFS and DFS traversals in trees.
The algorithm begins at the root node and then it explores each branch before backtracking. It is implemented using stacks. Often while writing the code, we use recursion stacks to backtrack. By using recursion we are able to take advantage of the fact that left and right subtrees are also trees and share the same properties.
For Binary trees, there are three types of DFS traversals.
This algorithm also begins at the root node and then visits all nodes level by level. That means after the root, it traverses all the direct children of the root. After all direct children of the root are traversed, it moves to their children and so on. To implement BFS we use a queue.
For Binary trees, we have Level Order Traversal which follows BFS.
Let the tree under consideration be:
The structure of TreeNode class is as follows :
In pre-order traversal of a binary tree, we first traverse the root, then the left subtree and then finally the right subtree. We do this recursively to benefit from the fact that left and right subtrees are also trees.
The algorithm for pre-order traversal is as follows:
The Pre-Order traversal of the tree above is:
The java code is as follows:
In-order traversal of a binary tree first traverses the left subtree then the root and finally the right subtree.
The algorithm for in-order traversal is as follows:
The in-order traversal of the tree above is:
The java code is as follows :
Post-order traversal of a binary tree first traverses the left subtree then the right subtree and then finally the root.
The algorithm for post-order traversal is as follows:
The post-order traversal of the tree above is:
The java code is as follows :
Level order traversal uses a queue to keep track of nodes to visit. After visiting a node, its children are put in the queue. To get a new node to traverse, we take out elements from the queue.
The algorithm is as follows:
Level order traversal of the tree above is :
The java code is as follows :
The complete Java code is given below :
This tutorial was about BFS and DFS traversals in binary trees. To get DFS implementation in C++ refer to this tutorial. For C++ implementation of level order traversal refer to this tutorial.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
How do i know which part is bfs or dfs
- Raj
where is the code for DFS?
- jd