In the attached code, printGivenLevel()
is O(n)
indeed for worst case.
The *complexity function) of printGivenLevel()
is:
T(n) = T(left) + T(right) + O(1)
where left = size of left subtree
right = size of right subtree
In worst case, for each node in the tree there is at most one son, so it looks something like this:
1
2
3
4
5
6
7
8
...
Now, note that the way the algorithm works, you start from the root, and travel all the way to the required level, while decreasing the level
variable every time you recurse. So, in order to get to the n
th level, you are going to need at least n
invokations of printGivenLevel()
, so the complexity function of printGivenLevel()
for the above example is:
T(n) = T(n-1) + T(1) + O(1) = O(n) (can be proved used master theorem)
The first implementation requires you to do printGivenLevel()
for each level, so for the same example, you get a worst case running time of O(n^2)
, since you need O(k)
to print each level from 1
to k
, which is O(1 + 2 + 3 + ... + n) =(*) O(n(n+1)/2) = O(n^2)
, where the equality marked with (*)
is from sum or arithmetic progression