Is the runtime of BFS and DFS on a binary tree O(N)?

♀尐吖头ヾ 提交于 2019-12-04 10:27:16

问题


I realize that runtime of BFS and DFS on a generic graph is O(n+m), where n is number of nodes and m is number of edges, and this is because for each node its adjacency list must be considered. However, what is the runtime of BFS and DFS when it is executed on a binary tree? I believe it should be O(n) because the possible number of edges that can go out of a node is constant (i.e., 2). Please confirm if this is the correct understanding. If not, then please explain what is the correct time complexity of BFS and DFS on a binary tree?


回答1:


The time complexities for BFS and DFS are just O(|E|), or in your case, O(m).

In a binary tree, m is equal to n-1 so the time complexity is equivalent to O(|V|). m refers to the total number of edges, not the average number of adjacent edges per vertex.




回答2:


Yes, O(n) is correct.

Also note that the number of edges can more exactly be expressed as the number of nodes - 1. This can quite easily be seen by considering that each node, except the root, has an edge from its parent to itself, and these edges cover all edges that exists in the tree.



来源:https://stackoverflow.com/questions/19901686/is-the-runtime-of-bfs-and-dfs-on-a-binary-tree-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!