程序将具有n个叶节点的平衡二叉搜索树作为输入,并为每个节点x计算函数g(x)的值。如果计算成本g(x)是min {否。 x的左子树中的叶节点数,否。 x}的右子树中叶节点的数量,那么程序的最坏情况时间复杂度是
(A) Θ(n)
(B) Θ(nLogn)
(C) Θ(n 2 )
(D) Θ(n 2 log n)答案: (B)
解释:
The recurrence relation for the recursive function is
T(N) = 2 * T(N/2) + n/2
Where N is the total no. of nodes in the tree.
T(N) = 2 * (2*T(N/2) + n/2) + n/2
= 4 * T(N/2) + 3(n/2)
Solve this till T(1) i.e. till we reach the root.
T(N) = c * T(N / 2^i) + (2*i - 1) * (n/2)
Where i = lg(N)
= lg((2n - 1) / 2)
O(c * T(N / 2^i) + (2*i - 1) * (n/2)) reduces to
O((2*i - 1) * (n/2))
O((2*( lg((2n - 1) / 2)) - 1) * (n/2)) ...sub the value of i.
O(n * ln(n))
资料来源:http://www.nid.iitkgp.ernet.in/DSamanta/courses/IT60101_2/Archives/Assignment-%20IC%20Binary%20Trees%20Solutions.pdf
这个问题的测验