Skip to content
Official PYQ · 2004

GATE CS 2004 Q85 — Binary Search Trees

Explain with AI

A program takes as input a balanced binary search tree with nn leaf nodes and computes the value of a function g(x)g(x) for each node xx. If the cost of computing g(x)g(x) is: min⁡(number of leaf-nodesin left-subtree of x  ,  number of leaf-nodesin right-subtree of x)\Large \min \left ( \substack{\text{number of leaf-nodes}\\\text{in left-subtree of $x$}}\;,\; \substack{\text{number of leaf-nodes}\\\text{in right-subtree of $x$}}\right )

Then the worst-case time complexity of the program is?

Choose one option
View worked solution

Answer: B

To find the worst-case time complexity of computing g(x)g(x) for all nodes in a balanced binary search tree with nn leaf nodes, we can set up a recurrence relation.

Let T(n)T(n) be the total cost of computing g(x)g(x) for all nodes in a balanced BST with nn leaf nodes.

  1. Cost at the root node: Since the binary search tree is balanced, the nn leaf nodes are distributed almost equally between the left and right subtrees. Thus, the left subtree has approximately n2\frac{n}{2} leaf nodes, and the right subtree has approximately n2\frac{n}{2} leaf nodes.
    The cost of computing g(root)g(\text{root}) is: Cost(root)=min⁡(n2,n2)=Θ(n)\text{Cost}(\text{root}) = \min\left(\frac{n}{2}, \frac{n}{2}\right) = \Theta(n)
  2. Recursive step: The total cost T(n)T(n) is the sum of the cost at the root and the costs of computing the function recursively for the left and right subtrees: T(n)=2T(n2)+Θ(n)T(n) = 2T\left(\frac{n}{2}\right) + \Theta(n)

Using Master's Theorem for the recurrence T(n)=aT(n/b)+f(n)T(n) = aT(n/b) + f(n) where a=2a = 2, b=2b = 2, and f(n)=Θ(n)f(n) = \Theta(n):

Since log⁡ba=log⁡22=1\log_b a = \log_2 2 = 1, and f(n)=Θ(n1)f(n) = \Theta(n^1), we fall into Case 2 of Master's Theorem. Therefore:

T(n)=Θ(nlog⁡22log⁡n)=Θ(nlog⁡n)\begin{align*} T(n) &= \Theta(n^{\log_2 2} \log n) \\ &= \Theta(n \log n) \end{align*}

Thus, the worst-case time complexity of the program is Θ(nlog⁡n)\Theta(n \log n).

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Binary Search Trees questions