I am trying to compute the depth of any(not necessarily complete) BST in O(log n) time recursively.
This is the algorithm I came up with:
//max() - returns the max of two numbers
int depth(root)
{
if(root->left==NULL && root->right==NULL) //leaf
return 0;
else if(root->left!=NULL && root->right==NULL) //with right leaf
return( max(depth(root->left),0)+1);
else if(root->left==NULL && root->right!=NULL) //with left leaf
return( max(0,depth(root->right)+1);
else if(root->left->left==NULL && root->left->right==NULL && root->right->left==NULL&&root->right->right==NULL) // this a parent of two leaves
return 1;
else// for the condition that this a parent of two sub roots
return( max(depth(root->right),depth(root->left))+1);
}
Is this algorithm fine for calculating depth in O(log n) time?
Is there a better way?