Open In App

Illustrate the difference in peak memory consumption between DFS and BFS

Last Updated : 20 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

To understand this let’s take a binary tree

Binary tree

If we conduct BFS in this tree:

  • In level 0 there is one node in the memory

Level-0 

  • In level 1 there are two nodes in the memory

Level-1

  • In level 2 there are four nodes in the memory

Level-2

  • In level 3 there are eight nodes in the memory

Level-3

But in the case of DFS in this tree, you’ll never have more than 4 nodes in memory

Depth-first search

The difference in peak memory consumption between DFS and BFS:

  • More specifically, BFS uses O(maxWidth) memory, whereas DFS only uses O(maxDepth).  The difference gets a lot worse as the tree goes larger.
  • The DFS generally needs less memory as it only has to keep track of the nodes in a chain from the top to the bottom, while the BFS has to keep track of all the nodes on the same level.
  • If there is a case where maxWidth < MaxDepth BFS will use less memory but this is rarely true.

So, we can conclude that the maximum space used by BFS or DFS is based on the structure of the tree. There can be cases when DFS takes less space than BFS and the opposite can also happen.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads