gkeenley
gkeenley

Reputation: 7378

Why is time complexity of recursive tree equal to number of leaf nodes instead of total number of nodes?

I'm looking at the time and space complexity of the simple recursive function below:

enter image description here

It has time complexity O(2^n), which is the number of leaf nodes. But there is a function call at every node of the tree. Why is the time complexity equal to the number of leaf nodes and not the total number of nodes?

Upvotes: 1

Views: 1172

Answers (2)

AntiMatterDynamite
AntiMatterDynamite

Reputation: 1512

the tree has a depth of 5 and 16 leaf nodes, last time i checked 2^5 is 32 not 16.... it's 2^n because there are 2^(n-1) + 2^(n-2) + ... + 2^1 nodes which comes to exactly 2^n-1 calls, discarding the -1 you get O(2^n)

Upvotes: 2

MrSmith42
MrSmith42

Reputation: 10151

Doesn't change the complexity if you count only the leaves or all nodes.

All non leave-Nodes are 2^n-1.
O(2^n + 2^n-1) = O(2^n).

Upvotes: 1

Related Questions