I want to analyze complexity of traversing a BST. I directly thought that its complexity as $O(2^n)$ because there are two recursive cases. I mean $T(n) = constants + 2T(n-1)$. However, AFAI research it is $O(n)$. Can you show it how come and my wrong?

void printInorder(Node node) 
        if (node == null)     // I think it is T(0) = 1
            return;           // constant c

        /* first recur on left child */
        printInorder(node.left);     // T(n-1)

        /* then print the data of node */
        System.out.print(node.key + " "); //constant(c)

        /* now recur on right child */
        printInorder(node.right); //T(n-1)

In order to analyse the time complexity of a tree traversal you have to think in the terms of number of nodes visited. If a tree has $n$ nodes, then each node is visited only once in inorder traversal and hence the complexity is $O(n)$.

Here, the input is in terms of number of nodes in the tree and the hence the complexity.

The notion that each recursive call is $T(n-1)$ is wrong. Let say we have a tree that has three children to the left of root and three children to the right of root. So n = 7. Now when you visit root then you have two paths. One to left which has 3 children and one to right which also has 3 children. But $7-1 \neq 3$. Hence this notion of 2 recursive calls of $T(n-1)$ is wrong.

It totally depends on the structure of the tree. In worst case a tree may degenerate to linked list (a skew tree having children on only one side either left or right) and we know well that traversal of linked list is $O(n)$, for a list of n elements. Hence, also the worst case is $O(n)$.

| cite | improve this answer | |

The Big-O notation in simple terms could be said as the number of operations performed.

In the recursive function of yours, there are no internal loopings that add to an additional degree of operations. You may trace out this function and see how many times the function call happens which will make you more clear on understanding the recursive function.

Breaking down your function, for each time printInorder(n) is called,

  • checks if n is null
  • calls printInorder on n -> leftNode
  • prints n -> value
  • calls printInorder on n -> right node

So for every call of this function with a particular n a maximum of 4 operations are performed. (it will either be 4 if n != null and 1 if n == null). When you trace down the function on any binary tree, you may notice that the function call happens for (only) a single time on each node in the tree. So you can say a max of k*n operations (k << n, k <= 4 in this case) have been done in this function and so in terms of Big-O has an O(n) complexity.

| cite | improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.