The Wayback Machine - https://web.archive.org/web/20241126030403/https://www.geeksforgeeks.org/bfs-vs-dfs-binary-tree/
Open In App

BFS vs DFS for Binary Tree

Last Updated : 19 Feb, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Breadth-First Search (BFS) and Depth-First Search (DFS) for Binary Trees are ways to traverse nodes of the Binary Tree. This article aims to provide the basic difference between BFS and DFS for Binary Tree.

A Tree is typically traversed in two ways:

  1. Breadth First Traversal (Or Level Order Traversal)
  2. Depth First Traversals
    • Inorder Traversal (Left-Root-Right)
    • Preorder Traversal (Root-Left-Right)
    • Postorder Traversal (Left-Right-Root)

BFS vs DFS for Binary Tree

What is Breadth First Search?

Breadth First Search (BFS) is a graph traversal algorithm that starts traversing the graph from the root node and explores all the neighboring nodes at the present depth prior to moving on to the nodes at the next depth level.

How does BFS Tree Traversal work?

Breadth First Search (BFS) traversal explores all the neighboring nodes at the present depth prior to moving on to the nodes at the next depth level. In the context of a tree, BFS traversal works similarly.

Here’s how BFS tree traversal typically works:

  1. Start at the root node and add it to a queue.
  2. While the queue is not empty, dequeue a node and visit it.
  3. Enqueue all of its children (if any) into the queue.
  4. Repeat steps 2 and 3 until the queue is empty.

This approach ensures that nodes are visited level by level, moving horizontally across the tree before moving to the next level. This way, BFS explores the nodes in a breadth-first manner, making it useful for tasks like finding the shortest path in unweighted graphs or trees.

What is a Depth-first search?

DFS (Depth-first search) is a technique used for traversing trees or graphs. Here backtracking is used for traversal. In this traversal first, the deepest node is visited and then backtracks to its parent node if no sibling of that node exists

1. Inorder Traversal (Practice):

Follow the below steps to solve the problem:

  • Traverse the left subtree, i.e., call Inorder(left-subtree)
  • Visit the root
  • Traverse the right subtree, i.e., call Inorder(right-subtree)

2. Preorder Traversal (Practice):

Follow the below steps to solve the problem:

  • Visit the root
  • Traverse the left subtree, i.e., call Preorder(left-subtree)
  • Traverse the right subtree, i.e., call Preorder(right-subtree)

3. Postorder Traversal (Practice):

Follow the below steps to solve the problem:

  • Traverse the left subtree, i.e., call Postorder(left-subtree)
  • Traverse the right subtree, i.e., call Postorder(right-subtree)
  • Visit the root.

Difference Between BFS and DFS:

Parameters BFS DFS
Stands for BFS stands for Breadth First Search. DFS stands for Depth First Search.
Data Structure BFS(Breadth First Search) uses Queue data structure for finding the shortest path. DFS(Depth First Search) uses Stack data structure.
Definition BFS is a traversal approach in which we first walk through all nodes on the same level before moving on to the next level.   DFS is also a traversal approach in which the traverse begins at the root node and proceeds through the nodes as far as possible until we reach the node with no unvisited nearby nodes.
Conceptual Difference BFS builds the tree level by level. DFS builds the tree sub-tree by sub-tree.
Approach used It works on the concept of FIFO (First In First Out).  It works on the concept of LIFO (Last In First Out).
Suitable for BFS is more suitable for searching vertices closer to the given source. DFS is more suitable when there are solutions away from source.
Applications BFS is used in various applications such as bipartite graphs, shortest paths, etc. DFS is used in various applications such as acyclic graphs and finding strongly connected components etc.

Conclusion

BFS and DFS are both efficient algorithms for traversing binary trees. The choice of which algorithm to use depends on the specific application and the desired traversal order. BFS is preferred when the goal is to visit all nodes at the same level, while DFS is preferred when exploring a branch as far as possible is more important.


Previous Article
Next Article

Similar Reads

Illustrate the difference in peak memory consumption between DFS and BFS
To understand this let's take a binary tree If we conduct BFS in this tree: In level 0 there is one node in the memory In level 1 there are two nodes in the memory In level 2 there are four nodes in the memory In level 3 there are eight nodes in the memory But in the case of DFS in this tree, you'll never have more than 4 nodes in memory The differ
1 min read
When to use DFS or BFS to solve a Graph problem?
Generally, when we come across a graph problem, we might need to traverse the structure of the given graph or tree to find our solution to the problem. Our problem might be : To search for a particular node in the graph.To find the shortest distance from a node to any other node or to every other node.To count all the nodes.Or there can be more com
7 min read
Why is the complexity of both BFS and DFS O(V+E)?
The complexity of both BFS and DFS are O(V+E) because every vertex (V) and every edge (E) is explored only once. In graph theory, two fundamental algorithms used for traversing or searching tree or graph data structures are Breadth-First Search (BFS) and Depth-First Search (DFS). Let's look at Why is the complexity of both BFS and DFS is O(V+E). Wh
2 min read
Time and Space Complexity of DFS and BFS Algorithm
The time complexity of both Depth-First Search (DFS) and Breadth-First Search (BFS) algorithms is O(V + E), where V is the number of vertices and E is the number of edges in the graph. The space complexity of DFS is O(V), where V represents the number of vertices in the graph, and for BFS, it is O(V), where V represents the number of vertices in th
2 min read
Difference between BFS and DFS
Breadth-First Search (BFS) and Depth-First Search (DFS) are two fundamental algorithms used for traversing or searching graphs and trees. This article covers the basic difference between Breadth-First Search and Depth-First Search. ParametersBFSDFSStands forBFS stands for Breadth First Search.DFS stands for Depth First Search.Data StructureBFS(Brea
2 min read
Distance of each node of a Binary Tree from the root node using BFS
Given a Binary tree consisting of N nodes with values in the range [1, N], the task is to find the distance from the root node to every node of the tree. Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 Output: 0 1 1 2 2 2 Explanation: The distance from the root to node 1 is 0. The distance from the root to node 2 is 1. The distance from the root to node 3 i
9 min read
Check if two nodes are cousins in a Binary Tree using BFS
Given a binary tree (having distinct node values) root and two node values. The task is to check whether the two nodes with values a and b are cousins. Note: Two nodes of a binary tree are cousins if they have the same depth with different parents. Example: Input: a = 5, b = 4 Output: TrueExplanation: Node with the values 5 and 4 are on the same le
11 min read
Level Order Traversal (Breadth First Search or BFS) of Binary Tree
Level Order Traversal technique is defined as a method to traverse a Tree such that all nodes present in the same level are traversed completely before traversing the next level. Example: Input: Output:12 34 5 How does Level Order Traversal work?The main idea of level order traversal is to traverse all the nodes of a lower level before moving to an
11 min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Diameter of n-ary tree using BFS
N-ary tree refers to the rooted tree in which each node having atmost k child nodes. The diameter of n-ary tree is the longest path between two leaf nodes. Various approaches have already been discussed to compute diameter of tree. Diameter of an N-ary tree Diameter of a Binary Tree in O(n) Diameter of a Binary Tree Diameter of a tree using DFS Thi
7 min read
Count the number of nodes at given level in a tree using BFS.
Given a tree represented as an undirected graph. Count the number of nodes at a given level l. It may be assumed that vertex 0 is the root of the tree. Examples: Input : 7 0 1 0 2 1 3 1 4 1 5 2 6 2 Output : 4 Input : 6 0 1 0 2 1 3 2 4 2 5 2 Output : 3 BFS is a traversing algorithm that starts traversing from a selected node (source or starting node
9 min read
Check if the given permutation is a valid BFS of a given Tree
Given a tree with N nodes numbered from 1 to N and a permutation array of numbers from 1 to N. Check if it is possible to obtain the given permutation array by applying BFS (Breadth First Traversal) on the given tree.Note: Traversal will always start from 1.Example: Input: arr[] = { 1 5 2 3 4 6 } Edges of the given tree: 1 - 2 1 - 5 2 - 3 2 - 4 5 -
10 min read
Level of Each node in a Tree from source node (using BFS)
Given a tree with v vertices, find the level of each node in a tree from the source node. Examples: Input : Output : Node Level 0 0 1 1 2 1 3 2 4 2 5 2 6 2 7 3 Explanation : Input: Output : Node Level 0 0 1 1 2 1 3 2 4 2 Explanation: Approach: BFS(Breadth-First Search) is a graph traversal technique where a node and its neighbours are visited first
8 min read
0-1 BFS (Shortest Path in a Binary Weight Graph)
Given a graph where every edge has weight as either 0 or 1. A source vertex is also given in the graph. Find the shortest path from the source vertex to every other vertex.  For Example:  Input : Source Vertex = 0 and below graph Having vertices like(u,v,w): Edges: [[0,1,0], [0, 7, 1], [1,2,1], [1, 7, 1], [2, 3, 0], [2, 5, 0], [2, 8, 1], [3, 4, 1],
9 min read
Subtree of all nodes in a tree using DFS
Given n nodes of a tree and their connections, print Subtree nodes of every node.Subtree of a node is defined as a tree which is a child of a node. The name emphasizes that everything which is a descendant of a tree node is a tree too, and is a subset of the larger tree. Examples : Input: N = 5 0 1 1 2 0 3 3 4 Output: Subtree of node 0 is 1 2 3 4 S
8 min read
Queries for DFS of a subtree in a tree
Given a tree of N nodes and N-1 edges. The task is to print the DFS of the subtree of a given node for multiple queries. The DFS must include the given node as the root of the subtree. In the above tree, if 1 is given as the node, then the DFS of subtree will be 1 2 4 6 7 5 3.If 2 is given as the node, then the DFS of the subtree will be 2 4 6 7 5.
11 min read
Tree, Back, Edge and Cross Edges in DFS of Graph
Consider a directed graph given in below, DFS of the below graph is 1 2 4 6 3 5 7 8. In below diagram if DFS is applied on this graph a tree is obtained which is connected using green edges. Tree Edge: It is an edge which is present in the tree obtained after applying DFS on the graph. All the Green edges are tree edges. Forward Edge: It is an edge
11 min read
Level with maximum number of nodes using DFS in a N-ary tree
Given a N-ary tree, the task is to print the level with the maximum number of nodes. Examples: Input : For example, consider the following tree 1 - Level 1 / \ 2 3 - Level 2 / \ \ 4 5 6 - Level 3 / \ / 7 8 9 - Level 4 Output : Level-3 and Level-4 Approach: Insert all the connecting nodes to a 2-D vector tree.Run a DFS on the tree such that height[n
10 min read
Find the Kth node in the DFS traversal of a given subtree in a Tree
Given a tree with N nodes, and two integers K and V. The task is to find the Kth node in the DFS traversal of the vertex V.Consider the below Tree: DFS of node number 1 is [1, 2, 3, 5, 6, 8, 7, 9, 4]. DFS of node number 3 is [3, 5, 6, 8, 7, 9] DFS of node number 7 is [7, 9] DFS of node number 9 is [9]. Print "-1" if the numbers in the DFS of vertex
10 min read
Construct the Rooted tree by using start and finish time of its DFS traversal
Given start and finish times of DFS traversal of N vertices that are available in a Rooted tree, the task is to construct the tree (Print the Parent of each node). Parent of the root node is 0.Examples: Input: Start[] = {2, 4, 1, 0, 3}, End[] = {3, 5, 4, 5, 4} Output: 3 4 4 0 3 Given Tree is -: 4(0, 5) / \ (1, 4)3 2(4, 5) / \ (2, 3)1 5(3, 4) The ro
8 min read
Diameter of a tree using DFS
The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two leaves in the tree. The diagram below shows two trees each with a diameter of five, the leaves that form the ends of the longest path are shaded (note that there is more than one path in each tree of length five, but no path longer than five n
8 min read
DFS for a n-ary tree (acyclic graph) represented as adjacency list
A tree consisting of n nodes is given, we need to print its DFS. Examples : Input : Edges of graph 1 2 1 3 2 4 3 5 Output : 1 2 4 3 5 A simple solution is to do implement standard DFS. We can modify our approach to avoid extra space for visited nodes. Instead of using the visited array, we can keep track of parent. We traverse all adjacent nodes bu
4 min read
Count the number of nodes at a given level in a tree using DFS
Given an integer l and a tree represented as an undirected graph rooted at vertex 0. The task is to print the number of nodes present at level l. Examples:  Input: l = 2   Output: 4  We have already discussed the BFS approach, in this post we will solve it using DFS. Approach: The idea is to traverse the graph in a DFS manner. Take two variables, c
8 min read
DFS traversal of a Tree
Given a Binary tree, Traverse it using DFS using recursion. Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical way to traverse them, trees can be traversed in different ways. Generally, there are 2 widely used ways for traversing trees: DFS or Depth-First SearchBFS or Breadth-First Search What is a D
15+ min read
Convert a Generic Tree(N-array Tree) to Binary Tree
Prerequisite: Generic Trees(N-array Trees) In this article, we will discuss the conversion of the Generic Tree to a Binary Tree. Following are the rules to convert a Generic(N-array Tree) to a Binary Tree: The root of the Binary Tree is the Root of the Generic Tree.The left child of a node in the Generic Tree is the Left child of that node in the B
13 min read
Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
We have discussed Threaded Binary Tree. The idea of threaded binary trees is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Wherever a right pointer is NULL, it is used to store inorder successor. The following diagram sho
12 min read
Check whether a binary tree is a full binary tree or not | Iterative Approach
Given a binary tree containing n nodes. The problem is to check whether the given binary tree is a full binary tree or not. A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has only one child node. Examples: Input : 1 / \ 2 3 / \ 4 5 Outp
8 min read
Check whether a given binary tree is skewed binary tree or not?
Given a Binary Tree check whether it is skewed binary tree or not. A skewed tree is a tree where each node has only one child node or none. Examples: Input : 5 / 4 \ 3 / 2 Output : Yes Input : 5 / 4 \ 3 / \ 2 4 Output : No The idea is to check if a node has two children. If node has two children return false, else recursively compute whether subtre
13 min read
Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
Given two binary trees S and T, the task is the check that if S is a subtree of the Tree T. For Example: Input: Tree T - 1 / \ 2 3 / \ / \ 4 5 6 7 Tree S - 2 / \ 4 5 Output: YES Explanation: The above tree is the subtree of the tree T, Hence the output is YES Approach: The idea is to traverse both the tree in Pre-order Traversal and check for each
11 min read
Check whether a binary tree is a full binary tree or not
A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has one child node. More information about full binary trees can be found here. For Example : Recommended PracticeFull binary treeTry It! To check whether a binary tree is a full binary tre
14 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg