This recursive function has a problem and produces unexpected output.
It should go through the binary tree and search for a given node that holds data x using preorder depth first traversal.
After it finds the node it should return. I have two other functions for preorder and inorder traversal which work fine. This one does not stop when it finds the node, but keeps going up the callstack till it reaches the root and returns the root value of the tree. I have included all the functions below. The first one is the one that isn't working right.
//this one does not work
template<typename T>
inline typename BST<T>::Node* BST<T>::depth_first_postorder_s(Node* root,T x)
{
//if root is null
if (!root)
return nullptr;
depth_first_postorder_s(root->left,x);
depth_first_postorder_s(root->right,x);
if (root->data == x) {
return root;
}
}
template<typename T>
inline typename BST<T>::Node* BST<T>::depth_first_inorder_s(Node* root, T x)
{
//if root is null
if (!root)
return nullptr;
depth_first_inorder_s(root->left,x);
if (root->data == x) {
return root;
}
depth_first_inorder_s(root->right,x);
}
template<typename T>
inline typename BST<T>::Node* BST<T>::depth_first_preorder_s(Node* root,T x)
{
//if root is null
if (!root)
return nullptr;
if (root->data == x) {
return root;
}
depth_first_preorder_s(root->left,x);
depth_first_preorder_s(root->right,x);
}
root
ifroot->data
does not equalx
, they don'treturn
anything. – Daniel Langr