Saturday, January 11, 2025
Google search engine
HomeData Modelling & AIIllustrate the difference in peak memory consumption between DFS and BFS

Illustrate the difference in peak memory consumption between DFS and BFS

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.

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments