edited by
684 views
0 votes
0 votes

Suppose we have a balanced BST and we run a program on the BST with n leaf nodes and compute the value of a function $g(x)$ for each node in BST.

If the cost of computing $g(x)$ is minimum of number of leaf node in left subtree and number of leaf node in right subtree.

The worst case time complexity of the program is:

  1. $O(n)$
  2. $O(nlog_2n)$
  3. $O(n^2)$
  4. $O(n^2log_2n)$
edited by

1 Answer

1 votes
1 votes

It is balanced binary search tree .

We have total of logn levels (because tree is balanced) and cost at every level is O(n).

Hence total cost is= n*logn =O(n logn).

Alternatively:-

By using  Divide and conquer

we first need to count no. of leaf in left sub-tree, then no. of leaf in right sub-tree + compare them to find minimum.

T(n)=2T(n/2)+1   that gives complexity as O(n)

but we need to compute this for every node.

so, cost at 0 th level=O(n)

cost at 1st level=n/2+n/2=O(n)

cost at 2nd level=n/4+n/4+n/4+n/4=O(n)

we have total of logn levels (because tree is balanced) and cost at every level is O(n).

Hence total cost is  O( n log n)

Related questions

0 votes
0 votes
1 answer
2
Kashyap Avinash asked Nov 10, 2016
373 views
Number of comparision in searching an element in a binary search tree is ?