I attempting to search a binary tree for a provided value (10) returning either true or false but cannot complete the code... Any ideas where I went wrong?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
template< typename T >
staticbool search(BinaryTreeNode<T> * p, T val)
{
if ( root == NULL ) // empty tree
{
returnfalse
}
else // if the tree is not empty
{
int temp = (p->data == val)? returntrue : returnfalse;
int temp2 = search(p->left, val);
int temp3 = search(p->right, val);
}
}
No the function def is not inside the class def, but I dont think I should remove the template <typename T>...i do get all sorts of errors if I do remove it.
Oh yes, absolutely your right there - been looking at this for a while. Trying something like this now... but not getting a good return
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
template< typename T >
bool BinaryTree<T>::search(BinaryTreeNode<T> * p, T val)
{
if ( root == NULL ) // empty tree
{
returnfalse;
}
else // if the tree is not empty
{
if (val < p->data)
return(search(p->left, val));
elsereturn(search(p->right, val));
}
}
elseif (p->data < val) You should only do this if the tree is sorted. If it is not sorted you have to first call search on one of the child nodes and if that returns false you have to search the other child node as well.
Error 1 error C2597: illegal reference to non-static member 'ghvg::BinaryTree<T>::root'
and
Error 2 error C3867: 'ghvg::BinaryTree<T>::root': function call missing argument list; use '&ghvg::BinaryTree<T>::root' to create a pointer to member
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
template< typename T >
bool BinaryTree<T>::search(BinaryTreeNode<T> * p, T val)
{
if ( root == NULL ) // empty tree
{
returnfalse;
}
else // if the tree is not empty
{
if (val < p->data)
return(search(p->left, val));
elsereturn(search(p->right, val));
}
}