2,594 views
7 7 votes

A program takes as input a binary tree (not necessarily balanced) with $n$ nodes and computes for each node, the no. of leaf nodes in the sub-tree rooted at that node. The worst case time complexity of the program is

  1. $\Theta(n)$
  2. $\Theta(n \log n)$
  3. $\Theta\left(n^2 \right)$
  4. $\Theta\left(n^2 \log n \right)$

5 Answers

Best answer
12 12 votes

We just have to do a tree traversal and for leaf nodes return 1 and for other nodes call the function recursively on the left and right nodes and return their sum. The following code would do

int fun (node * x)
{
    if(!x) return 0;
    if(x -> left == NULL && x-> right == NULL) return 1;
    return fun(x->left) + fun(x->right);
}

And tree traversal is $\Theta(n)$.

• selected by
0 0 votes

Wouldn't the answer be O(n2) for a left or right skewed binary tree?

0 0 votes
ans should be O(n^2)..if tree is right skewed or left skewed then no of comparisons will be (n+ n-1 + n-2 +.......1) which is O(n^2)
0 0 votes
What would be the answer if, we are asked to compute number of nodes in the subtree rooted at each node of the binary tree?
Answer:
Position:
Show:

Related questions

1 1 vote
2 2 answers
937
937 views
Arjun asked Oct 10, 2016
937 views
Consider the following nested representation of Binary Trees.$(ABC)$ indicates $B$ and $C$ are left and right subtrees of node $A$ respectively. Note that $B$ and $C$ may...
0 0 votes
1 answers 1 answer
596
596 views
Arjun asked Oct 10, 2016
596 views
Consider the array given below:20 10 9 8 7 6 5It isa full binary tree in array representationa complete binary tree in array representationa max-heap in array representat...
2 2 votes
2 answers 2 answers
1.6k
1.6k views
Arjun asked Oct 10, 2016
1,641 views
With 5 distinct nodes, the maximum no. of binary trees that can be formed is _____
2 2 votes
3 answers 3 answers
2.5k
2.5k views
Arjun asked Oct 10, 2016
2,501 views
Which of the following statements is false?A tree with $n$ nodes has $n-1$ edgesA labeled rooted binary tree can be uniquely constructed given its in-order and pre-order ...