c++ - 即使在执行流程到达包含 while 的函数结束后,while 循环也会无限执行而无需任何递归调用

标签 c++ recursion while-loop stack binary-search-tree

下面是我用于 inorder 遍历 binary search tree 的函数。一切正常,直到循环 while(!st.empty()) 终止,但之后执行流程再次转到 while(!st.empty()) 因此循环变成无限循环

节点结构

class bst{ 
private:
    bst *lLink;
    int info;
    bst *rLink;

friend void inorder(bst &);
 };
void inorder(bst &);

调用部分

string c;
cout<<"\na, b or c ?";
cin>>c;

 if(c == "a")
 {
  inorder(nodeVec[0]);  //nodeVec is vector containing all nodes (objects) of tree with first element as root
 }

 //......

函数

void inorder(bst &item)
{
stack<bst> st;
st.push(item);


while((st.top()).getLeftChild()!=NULL)
{
    st.push(*((st.top()).getLeftChild()));
}

while(!st.empty())
{
    if(st.top().getInfo()==item.getInfo()) //true if traversal is done with all
                                           //left subtree of root and only oneitem remained in stack i.e. only root remained
    {                                     
        cout<<st.top().getInfo()<<endl;

        if(st.top().getRightChild()!=NULL)
            inorder(*(item.getRightChild()));

        else
            st.pop();
    }

    else{
    cout<<st.top().getInfo()<<endl;
    if(st.top().getRightChild()!=NULL)
    {
        bst curr=*(st.top().getRightChild());
        st.pop();
        st.push(curr);
    }
    else{
        st.pop();
    }
    }
}
 cout<<st.empty();  //for testing, this prints 1
} //execution goes here and then again at while(!st.empty())

假设树是这样的:

      69
     /  \
    43  89
   /   /
  24  73
 /
14
 \
  21

它给出输出

14
21
24
43
69
73
89
69   //loop starts again
73
89
69
73
89
...

最佳答案

当打印出来时,您应该从堆栈中删除该元素。

您将它留在 if() 的第一个 block 中的堆栈中,该 block 检查树的左侧是否已完成。

if(st.top().getRightChild()!=NULL)
    inorder(*(item.getRightChild()));

// else  // <--- don't use else here.. Always pop
    st.pop();

关于c++ - 即使在执行流程到达包含 while 的函数结束后,while 循环也会无限执行而无需任何递归调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19867656/

相关文章:

c++ - 为二叉搜索树创建一个新节点

c++ - 访问派生类成员的基类方法

python - 二叉搜索树删除中基本情况的目的

loops - Haskell 进行 IO 循环的方法(无需显式递归)?

java - 优化 Leaper Graph 算法?

java while 循环计数不正确

javascript - 检查/访问 QML 中动态创建的对象

c++ - 使用 Boost::Signals 进行 C++ 事件的完整示例

c - 为什么 while 语句的 "or"部分不起作用,但break语句却起作用?(对于 C)

c - 程序突然结束,C 中的 while 循环内有 switch case