Please note: this question not about the best implementation of algorithm, neither about datastructures.
Given a binary tree, it is required to verify that it is a bst
.
I am aware about much more efficient (O(n)
) algorithm, the question is not about it. I am practicing my big-O-estimation skills:
int isBST(struct node* node)
{
if (node == NULL)
return(true);
if (node->left!=NULL && maxValue(node->left) > node->data)
return(false);
if (node->right!=NULL && minValue(node->right) < node->data)
return(false);
if (!isBST(node->left) || !isBST(node->right))
return(false);
return(true);
}
..assuming that maxValue(...)/minValue(...)
are helper functions that each takes O(n)
to run.
If h
is the number of "levels" it has starting from the root and ending up with leaves. At each level both maxValue(...)
and minValue(...)
are called on the (n - 1) / 2^l
range, where l
is the current level. There are h
levels, so I expect to get something like (n - 1) / 1 + (n - 1) / 2 + (n - 1) / 4 + ... + (n - 1) / 2^h
. So it seems like O(n * h)
is a correct upper bound, is it?
Please verify my way of thinking.