View worked solution
Answer: 1
To find the number of subtrees having exactly nodes in a rooted binary tree of nodes, we can use a bottom-up (post-order) traversal approach.
For any node in the binary tree, the size of the subtree rooted at , denoted by , is given by:
where the size of a non-existent child (null pointer) is .
Algorithm:
- Perform a post-order traversal of the tree.
- For each node, compute its subtree size in time using the sizes of its left and right children (which are already computed due to the post-order nature of the traversal).
- Maintain a global counter. If , increment the counter.
Complexity Analysis:
- Since each node is visited exactly once and we perform a constant number of operations at each node, the total time complexity is .
- Thus, the best upper bound on the time required is .
We are given that the upper bound is . Comparing this with :
We need to find the value of :
Free practice · Your answers on this page are not saved.
