- 对于二叉树的遍历,一般是采用递归更加简洁明了,但是递归在效率上比起非递归差得太远。
- 以下代码采用非递归方式进行树的遍历,而且只需要改变输出语句的位置,就可以实现先、中、后序遍历,而无需更改整个程序的结构。
void traverse(){
stack<pair<Node*,int> > sk; //建立堆栈
sk.push(make_pair(root,1)); //将根节点放入栈里
while(!sk.empty()){
pair<Node*,int> t = sk.top();
if(t.second==1){
//cout<<t.first->c; //先序遍历采用这一句输出
sk.top().second++;
if(t.first->left){
sk.push(make_pair(t.first->left,1));
}
}
else if(t.second==2){
//cout<<t.first->c; //中序遍历采用这一句输出
sk.top().second++;
if(t.first->right)
sk.push(make_pair(t.first->right,1));
}
else{
//cout<<t.first->c; //后序遍历采用这一句输出
sk.pop();
}
}
cout<<endl;
}