zl程序教程

您现在的位置是:首页 >  工具

当前栏目

[Algorithm] BFS vs DFS

vs DFS BFS ALGORITHM
2023-09-14 08:59:14 时间
//If you know a solution is not far from the root of the tree:
BFS, because it is faster to get closer node

//If the tree is very deep and solutions are rare: 
BFS, DFS will take a longer time because of the deepth of the tree

//If the tree is very wide:
DFS, for the worse cases, both BFS and DFS time complexity is O(N).
But for the space complexity, DFS is O(H), where H is the height of the tree
BFS space complexity is O(W), where W is the width of the tree
As we know tree is very wide, W > H, so we choose DFS

//If solutions are frequent but located deep in the tree:
DFS, because we can find the node quickly

//Determining whether a path exists between two nodes:
DFS, it is good to check a path exists

//Finding the shortest path:
BFS, it is good to find shortest path