I wrote a function to search a Binary Search Tree, but I have logic problems: When I insert some values, and I have a tree of 2 levels, and the final level (2 in this case) is not full (full is that it does not have all child nodes) it returns 3, not 2:
// --- Definition of depth()
template<typename DataType>
int BST<DataType>::depth()
{
int counter = 0;
return Auxdepth(counter, myRoot);
}
// --- Definition of Auxdepth()
template<typename Datatype>
int BST<Datatype>::Auxdepth(int &counter, BinNodePointer subtree)
{
//BinNodePointer parameter is myRoot, which is the root node
int a;
int b;
if(empty()) return -1;// garbage value
if(subtree->left == 0 && subtree->right == 0)
return counter;
else if(subtree->left == 0){
int x = counter++;
a= Auxdepth(x,subtree->right);
return a;
}
else if(subtree->right == 0){
int x = counter++;
a = Auxdepth(x,subtree->left);
return a;
}
if(subtree != 0) { // Recursion
int x = counter + 1;
cout << "This is x " << x << endl;
a = Auxdepth(x, subtree->left);
b = Auxdepth(x, subtree->right);
if(a > b) return a;
else return b;
}
}
Note: The depth function is there just to be more friendly. Can anyone tell me where is my error?