下面是我用来inorder
遍历a 的函数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
...