Why does a breadth first search use more memory than depth first?

后端 未结 3 1926
囚心锁ツ
囚心锁ツ 2021-02-02 17:47

I can\'t find an answer to this online, and in other answers to questions similar to this it just seems to be a given that an advantage of DFS is that it uses less memory than D

3条回答
  •  耶瑟儿~
    2021-02-02 18:15

    BFS doesn't always use more memory. The tree you have, in particular, is an example where is doesn't.

    Consider this tree: (source)

    With BFS, at some stage, all nodes from 8-15 will be in memory.

    With DFS, you'll never have more than 4 nodes in memory (equal to the height of the tree).

    The difference gets a lot worse as the tree goes larger (as long as it stays fairly full).

    More specifically, BFS uses O(branchingFactor^maxDepth) or O(maxWidth) memory, where-as DFS only uses O(maxDepth).

    If maxWidth < maxDepth, BFS should use less memory (assuming you use similar representations for both), but this is rarely true.

提交回复
热议问题