edited by
24,581 views
90 votes
90 votes
Consider a rooted n node binary tree represented using pointers. The best upper bound on the time required to determine the number of subtrees having exactly $4$ nodes is $O(n^a\log^bn)$. Then the value of $a+10b$ is __________.
edited by

11 Answers

8 votes
8 votes
Simply do the post order traversal and keep track of number of nodes in left and right subtree.At any node when its left and right are processed,then check if left+right+1(for parent node)=4,then it means one subtree with 4 nodes encountered.

T.c => O(n) ,postorder
7 votes
7 votes
int result;
count(node n)
{
   if ( !n ) return 0;

   if ( n->left ) 
   { no_of_nodes_in_left_subtree = 1 + count ( n->left ) }

   if ( n->right ) 
   { no_of_nodes_in_right_subtree = 1 + count ( n->right ) }

   if ( no_of_nodes_in_left_subtree + no_of_nodes_in_right_subtree == 4 ) 
   { result ++; }

   return ( no_of_nodes_in_left_subtree + no_of_nodes_in_right_subtree ) ;

}

Every node is traversed once. Hence O(1) and answer a = 1; b =0.

2 votes
2 votes

DFS can calculate the number of nodes in a subtree. Time Complexity = $O(n+m)^{[*]}$

So, $O(n)$.

Hence, $a=1, \ b=0$

 

Answer is 1


$^{[*]}$ n is the number of nodes, m is the number of edges.

0 votes
0 votes

just use the function of counting nodes in the subtree . everytime the nodes of a subtree are counted just check if it is equal to yur requirement . time complexity of counting all  node in O(n) so this is also O(n).

function;;

int number(struct node *qwerty)
{int e,f,w;

    if(qwerty)
    {
        e=number(qwerty->left);   // number of node in left 
        f=number(qwerty->right);                   // number of node in right 
        if(e+f==4)                                 check requirement
        {
            count++;
        }
        w=1+e+f;        
      return w;
    }

Answer:

Related questions

101 votes
101 votes
10 answers
3