分别用了三种不同的方法实现了二叉树的后序遍历。
/*
input:
2
10 5 4 -1 -1 -1 20 19 -1 -1 40 -1 -1
30 10 8 20 -1 -1 -1 -1 50 40 -1 45 -1 -1 -1
output:
4 5 19 40 20 10
20 8 10 45 40 50 30
*/
#include<iostream>
#include<stack>
using namespace std;
struct BTreeNode{
//二叉树
int data;
BTreeNode *lchild;
BTreeNode *rchild;
BTreeNode *parent;
};
struct snode{
//设置访问标识
BTreeNode *node;
bool flag;
};
/*
void PostOrder(BTreeNode *t){
//递归方法
if(t == NULL)return ;
PostOrder(t->lchild);
PostOrder(t->rchild);
cout<<t->data<<' ';
}
*/
/*
void PostOrder(BTreeNode *t){
//设置访问标识,第一次为访问完左子树,第二次为访问完右子树。二次访问即刻输出结点。
stack<snode> s;
snode temp;
while(!s.empty() || t != NULL){
while(t != NULL){
temp.node = t;
temp.flag = false;
s.push(temp);
t = t->lchild;
}
if(!s.empty()){
temp = s.top();
s.pop();
t = temp.node;
if(temp.flag){
cout<<t->data<<' ';
t = NULL;
}
else{
temp.flag = true;
s.push(temp);
t = t->rchild;
}
}
}
}
*/
void PostOrder(BTreeNode *t){
//采取根右左的存放方式,用栈实现后序遍历。设置访问标识,注意第一次放入栈,放入的是根,第二次调整其顺序。
stack<snode> s;
snode temp,ltemp,rtemp;
temp.node = t;
temp.flag = false;
s.push(temp);
while(!s.empty()){
temp = s.top();
s.pop();
if(temp.flag)cout<<temp.node->data<<' ';
else{
temp.flag = true;
s.push(temp);
if(temp.node->rchild != NULL){
rtemp.flag = false;
rtemp.node = temp.node->rchild;
s.push(rtemp);
}
if(temp.node->lchild != NULL){
ltemp.flag = false;
ltemp.node = temp.node->lchild;
s.push(ltemp);
}
}
}
}
void Create(BTreeNode *&t){
//(测试用)以先序遍历构建二叉树
int x;
cin>>x;
if(x == -1)
t = NULL;
else
{
t = new BTreeNode;
t->data = x;
Create(t->lchild);
Create(t->rchild);
}
}
int main(){
BTreeNode *root = NULL;
int t;
cin>>t;
while(t--)
{
Create(root);
PostOrder(root);
cout<<endl;
}
return 0;
}