679 views
3 votes
3 votes
Below is a question I was asked in an Interview

What is the best case time complexity to find the height of a Binary Search Tree?

I answered it explaining using the below algorithm

int height(struct node *root)

{

  if(root==NULL) return 0;

  if(root->leftChild==NULL && root->rightChild==NULL)

  return 0;

  else

  { int c=0,lh,rh;

    lh=height(root->leftChild); ............(A)

    rh=height(root->rightChild); ...............(B)

    c=1+max(lh,rh);........................(C)

     return c;

   } //end of else

  
} //end of function height.

So, in best Case, my recurrence would become

$T(n)=2T(\frac{n}{2}) + c$

$T(\frac{n}{2})$ for each of line A and B, and constant time for Line C, and even for best case Complexity is $O(n)$.

Now, in the worst case, my recurrence would become

$T(n)=T(n-1)+c$

and this would be a case of a skewed BST.
Still, here complexity remains to be $O(n)$.

So, in all cases, the time complexity to find the height of a BST remains to be $O(n).$

Was my claim correct?

Please log in or register to answer this question.

Related questions

754
views
0 answers
0 votes
Vaishnavi01 asked Sep 28, 2018
754 views
697
views
0 answers
0 votes
AIkiran01 asked Aug 5, 2018
697 views
Is there any graph whose number of BFS and DFS traversals are different?If so which graph.
861
views
3 answers
1 votes
slowpoke asked May 8, 2017
861 views
Which sequence If inserted in AVL tree will cause No adjustment in tree? a) 1 2 3 4 5 ... d) 4 3 1 2 5
1.2k
views
1 answers
1 votes
shraddha priya asked May 19, 2019
1,190 views
Implement Linked list using stack.