Search code examples
binary-treedepth-first-searchtraversalbreadth-first-searchtree-traversal

Time complexity of BFS and DFS on a BinaryTree: Why O(n)?


The time complexity of BFS, or DFS, on a graph is O(V+E) because we traverse all the nodes and edges of the graph. (I get that) But for a binary tree, the time complexity of BFS and DFS is O(V)... Why is that?

I am assuming is because of the following: O(V+E) = O(V + V-1) = O(2V) = O(V). Is this the correct reasoning? If not, an intuitive explanation would be much appreciated. Thanks


Solution

  • All trees have n - 1 edges, n being the number of nodes. The time complexity is still technically O(V + E), but that equates to O(n + (n-1)) = O(n).