【问题标题】:Depth First search using postorder traversal recursion produces unexpected output使用后序遍历递归的深度优先搜索产生意外的输出
【发布时间】: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-&gt;data 不等于x,则return 不是任何东西。

标签: c++ recursion binary-search-tree depth-first-search


【解决方案1】:

您的代码中的所有函数似乎都无效。但是因此,正如您所说,第一个给您的值是错误的,因此对该函数的修改应该是 -

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

其他功能应类似实现。

【讨论】:

  • 就像一个魅力。谢谢你的建议,我不太擅长递归。
猜你喜欢
  • 2019-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-20
  • 2015-12-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多