Consider a rooted n node binary tree represented using pointers. The b...
struct node
{
int data;
node * left;
node * right;
};
The function to calculate the number of subtrees having exactly 4 nodes is as follows:
int subtrees_size_4(node *n)
{
int size=0;
if(node==null)
return 0;
size=subtrees_size_4(node->left)+subtrees_size_4(node->right)+1;
if(size==4)
printf("Subtree of size 4 found");
return size;
}
The running time of the above function is O(n).
Hence , a=1 , b=0. Hence , a+10b = 1
ANSWER : 1
View all questions of this test
Consider a rooted n node binary tree represented using pointers. The b...
Explanation:
To determine the number of subtrees having exactly 4 nodes in a rooted binary tree represented using pointers, we can use a recursive approach. Let's analyze the time complexity of this approach.
Recursive Approach:
1. Start from the root of the binary tree.
2. Recursively count the number of nodes in each subtree.
3. If the count is exactly 4, increment the counter for subtrees with exactly 4 nodes.
4. Repeat steps 2 and 3 for the left and right subtrees of the current node.
5. Return the total count of subtrees with exactly 4 nodes.
Time Complexity Analysis:
To determine the time complexity of the recursive approach, we need to consider the number of operations performed at each level of the recursion tree.
Let's assume the number of nodes in the binary tree is "n".
- At the root level, we perform a constant number of operations to check if the count is 4 and increment the counter. This takes O(1) time.
- At each subsequent level, the number of nodes decreases by approximately half.
- Therefore, the total number of levels in the recursion tree is log2(n).
At each level, we perform a constant number of operations, so the time complexity per level is O(1).
The total time complexity of the recursive approach can be calculated by multiplying the time complexity per level by the number of levels.
Total time complexity = O(1) * log2(n) = O(log n)
Calculation of a and b:
Given that the best upper bound on the time complexity is O(n^a log n^b), we can equate it to O(log n) as calculated above.
O(n^a log n^b) = O(log n)
Comparing the powers of n on both sides, we get:
a = 0 (since n^a = 1)
b = 1 (since log n^b = log n)
Therefore, the value of a is 0 and the value of 10b is 10^1 = 10.
Hence, the correct answer is 1.
To make sure you are not studying endlessly, EduRev has designed Computer Science Engineering (CSE) study material, with Structured Courses, Videos, & Test Series. Plus get personalized analysis, doubt solving and improvement plans to achieve a great score in Computer Science Engineering (CSE).