簡體   English   中英

使用后序遍歷遞歸的深度優先搜索會產生意外的 output

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM