0

assume I have a complete binary tree up-to a certain depth d. What would the time complexity be to traverse (pre-order traversal) this tree.

I am confused because I know that the amount of nodes in the tree is 2^d, so therefore the time complexity would be BigO(2^d) ? because the tree is growing exponentially.

But, upon research on the internet, Everyone states that's traversal is BigO(n) where n is the number of elements (which would be 2^d in this case), not BigO(2^d), what am I missing?

thanks

dgamma3
  • 2,333
  • 4
  • 26
  • 47

2 Answers2

3

n is defined as the number of nodes.

2^d is only the number of nodes when every possible node at that depth is full

ie.

     o
   /   \
  o     o
 / \   
o   o

only has 5 nodes when 2^d is 8

A complete binary tree has every node filled except for last row and all of the nodes are filled to the left. You can find the definition on wikipedia

http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees

Ian Armit
  • 673
  • 5
  • 10
  • my question is, if its a complete tree, I.e. totally full – dgamma3 Oct 23 '12 at 23:56
  • This is correct, except the number of nodes if the last row is full is 2^d - 1. It's worth noting also that since 2^(d-1) <= n <= 2^d - 1, it follows that O(n) = O(2^d). – kaya3 Nov 11 '19 at 20:22
0

Even if you can express the time complexity as O(2^d), that's pretty useless as it's not something that you can use to compare it to the time complexity of any other collection.

Expressing the time complexity as O(n) is on the other hand very useful. It tells you exactly how the collection reacts when you increase the number of items, without having to know exactly how the collection is implement, and you can compare it to the time complexity of other collections.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • so what your saying is, effectively it doesn't matter which one I pick. but bigO(n) is more intuitive. – dgamma3 Oct 23 '12 at 23:59
  • dont really understand why O(2^d) is unless, is this because the bound is so high? – dgamma3 Oct 24 '12 at 00:00
  • @dgamma3: It's pretty useless because you have to know how the tree is implemented, otherwise it tells you nothing about how the collection reacts when you add more items to it. – Guffa Oct 24 '12 at 00:08