【发布时间】:2020-03-14 21:27:50
【问题描述】:
这个递归函数有问题,产生了意外的输出。
它应该通过二叉树并使用前序深度优先遍历搜索保存数据 x 的给定节点。
找到节点后它应该返回。我还有另外两个用于预排序和中序遍历的函数,它们可以正常工作。这一个在找到节点时并没有停止,而是继续向上调用堆栈直到它到达根并返回树的根值。 我已经包含了以下所有功能。第一个是不正确的。
//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);
}
【问题讨论】:
-
所有函数seem to be invalid — 如果
root->data不等于x,则return不是任何东西。
标签: c++ recursion binary-search-tree depth-first-search