Open In App
Related Articles

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

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report
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

Last Updated : 28 Jun, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads