[英]Depth First search using postorder traversal recursion produces unexpected output
这个递归的 function 有问题,会产生意外的 output。
它应该通过二叉树 go 并使用前序深度优先遍历搜索保存数据 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);
}
您的代码中的所有功能似乎都无效。 但是因此,正如您所说,第一个给您的值是错误的,因此对 function 的修改应该是-
inline typename BST<T>::Node* BST<T>::depth_first_postorder_s(Node* root,T x)
{
//if root is null
if (!root)
return nullptr;
Node *lft = depth_first_postorder_s(root->left,x);
Node *rgt = depth_first_postorder_s(root->right,x);
if (root->data == x) {
return root;
} else if(lft != nullptr) {
return lft;
} else {
return rgt;
}
}
在这里,您需要将节点返回到等于x
的上一个递归调用。
其他功能应该类似地实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.