Open In App
Related Articles

GATE | GATE-CS-2014-(Set-1) | Question 21

Improve Article
Improve
Save Article
Save
Like Article
Like

Consider a rooted Binary tree represented using pointers. The best upper bound on the time required to determine the number of subtrees having having exactly 4 nodes O(na Logn b). Then the value of a + 10b is ________
(A) 1
(B) 11
(C) 12
(D) 21


Answer: (A)

Explanation: We can find the subtree with 4 nodes in O(n) time. Following can be a simple approach.
1) Traverse the tree in bottom up manner and find size of subtree rooted with current node
2) If size becomes 4, then print the current node.

Following is C implementation




#include<stdio.h>
#include<stdlib.h>
  
struct Node
{
    int data;
    struct Node *left, *right;
};
  
// A utility function to create a new Binary Tree Node
struct Node *newNode(int item)
{
    struct Node *temp =  (struct Node *)malloc(sizeof(struct Node));
    temp->data = item;
    temp->left = temp->right = NULL;
    return temp;
}
  
int print4Subtree(struct Node *root)
{
    if (root == NULL)
      return 0;
    int l =  print4Subtree(root->left);
    int r =   print4Subtree(root->right);
    if ((l + r + 1) == 4)
       printf("%d ", root->data);
    return (l + r + 1);
}
  
// Driver Program to test above functions
int main()
{
    struct Node *root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    root->right->left = newNode(6);
    root->right->right = newNode(7);
    root->right->left->right = newNode(8);
  
    print4Subtree(root);
  
    return 0;
}



Quiz of this Question


Level Up Your GATE Prep!
Embark on a transformative journey towards GATE success by choosing Data Science & AI as your second paper choice with our specialized course. If you find yourself lost in the vast landscape of the GATE syllabus, our program is the compass you need.

Last Updated : 28 Jun, 2021
Like Article
Save Article
Previous
Next
Similar Reads