0

I have the following pseudo-code for printing all nodes of a BST :

traverse(x):
    if x == nil:
        return
    else:
        print x
        traverse(x.left)
        traverse(x.right)

I want to find its complexity. I have an idea, but I'm not sure if I am implementing it correctly.

$T(n) = 2T(n-1) + cn$

Where $T(n-1)$ for each recursive call and $cn$ for the return statement.

Is my solution correct?

buydadip
  • 199
  • 4

3 Answers3

1

What i said in previous reply was about finding a node. I excuse for misunderstanding your question. For worst case its the same but for printing in average case it's $T(n)=2T(n/2)+1$ which is $O(n)$.

hengxin
  • 9,671
  • 3
  • 37
  • 75
n.Perception
  • 131
  • 6
1

It sometimes helps to start by seeing what an algorithm does, rather than immediately jumping to computing the timing. In your case, you're generating a preorder traversal of a binary tree:

visit (node x)                // x is the root node of the tree being visited
   if x exists
      print the value in x
      visit (x's left subtree)
      visit (x's right subtree)

For example, consider this binary tree: enter image description here

Starting at the root, we print its value, $5$, and then recursively visit the left subtree (the $2, 8, 4$ piece). The root of that subtree is the $2$ node, so that would be printed next. Continuing this way, we print $5, 2, 8, 4$ and backtrack from the $4$ node to the $8$ node, continuing until we find a right subtree to visit, namely the right subtree of the $5$ node. We then visit the $7, 1, 3, 6$ subtree, from left to right at each subtree. The traversal will then be $$ 5\quad2\quad8\quad4\quad7\quad1\quad3\quad6 $$ Now that we see what the algorithm does, let's see how long it takes. There are two important parts: printing the node values and then recursively printing the values in the left and right subtrees. For a tree with $n$ nodes we'll print $n$ values. We get to each of these print statements as part of a function call, so there will also be $n$ function calls. The total amount of work done, then will be $2n$ so $T(n)=\Theta(n)$. Note that the timing will not depend on the shape of the tree, only on the number of nodes in the tree.

Rick Decker
  • 15,016
  • 5
  • 43
  • 54
0

Complexity of a BST differs in different cases. In worst case BST is is like a linear linked list (all sub nodes are only left-child or right-child of each other) which its complexity can be measured by solving following recursive equation:

$T(n)=T(n-1)+1$ which is $O(n)$. But for average case we can consider it as a complete binary tree so $T(n)=T(n/2)+1$ and it's complexity is $O(log(n))$ which $log(n)$ is height of the tree.

n.Perception
  • 131
  • 6