[英]while loop executing infinitely without any recursive call even after execution flow reaches end of function containing while
below is a function i am using for inorder
traversal of a binary search tree
. 下面是我使用的功能
inorder
一的遍历binary search tree
。 Everything works well till the loop while(!st.empty())
gets terminated but after that the execution flow again goes to while(!st.empty())
hence loop turns into an infinite loop 一切顺利,直到循环,
while(!st.empty())
被终止但在此之后执行流程再次进入while(!st.empty())
因此循环变成无限循环
structure of node 节点结构
class bst{
private:
bst *lLink;
int info;
bst *rLink;
friend void inorder(bst &);
};
void inorder(bst &);
calling part 呼叫部分
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
}
//......
function 功能
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())
suppose the tree is like this: 假设树是这样的:
69
/ \
43 89
/ /
24 73
/
14
\
21
it gives output 它给出了输出
14
21
24
43
69
73
89
69 //loop starts again
73
89
69
73
89
...
You should be removing the element from the stack when it's printed out. 您应该在打印出来时从堆栈中删除该元素。
You're leaving it on the stack in the first block of the if() that checks that the left side of the tree has been completed. 您将它留在if()的第一个块中的堆栈上,该块检查树的左侧是否已完成。
if(st.top().getRightChild()!=NULL)
inorder(*(item.getRightChild()));
// else // <--- don't use else here.. Always pop
st.pop();
This seems way more complicated than it needs to be, Here is a untested version of what I think would work better. 这似乎比它需要的更复杂,这是我认为可以更好地工作的未经测试的版本。
struct bst{
int info;
bst *right;
bst *left;
};
void inorder(bst & item) {
std::stack<bst*> st;
bst* current = &item;
while(current || !st.empty()) {
if(current) {
st.push(current);
current = current->left;
} else {
current = st.top();
st.pop();
std::cout << current->info << std::endl;
current = current->right;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.