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 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.
My Personal Notes arrow_drop_up
Please Login to comment...