DS二叉树--后序遍历非递归算法
题目描述
求一颗树的后序遍历的非递归算法
要求:必须是非递归算法,使用堆栈对象来实现
建树方法采用“先序遍历+空树用0表示”的方法
算法流程:

输入
第一行输入一个整数t,表示有t个测试数据
第二行起输入二叉树先序遍历的结果,空树用字符‘0’表示,输入t行
输出
逐行输出每个二叉树的后序遍历结果
样例输入
3 AB0C00D00 ABC00D00EF000 ABCD0000E0F00
样例输出
CBDA CDBFEA DCBFEA
提示
#include<iostream>
#include<stack>
using namespace std;
class CNode
{
public:
char data;
CNode *left;
CNode *right;
CNode()
{
left=right=NULL;
}
};
class BiTree
{
public:
CNode *Root;
int pos;
string strTree;
BiTree(string str)
{
pos=0;
strTree=str;
Root=CreateBiTree();
}
CNode *CreateBiTree()
{
CNode *T;
char ch;
ch=strTree[pos];
pos++;
if(ch==‘0‘)
{
T=NULL;
}
else
{
T=new CNode();
T->data=ch;
T->left=CreateBiTree();
T->right=CreateBiTree();
}
return T;
}
void nonPre()
{
CNode *T=Root;
stack<CNode*>S;
while(T||!S.empty())
{
while(T)
{
cout<<T->data;
S.push(T);
T=T->left;
}
if(!S.empty())
{
T=S.top();
S.pop();
T=T->right;
}
}
}
void nonPost()
{
int tag;///0不可访问,1可访问
stack<CNode*>S1;///结点
stack<int>S2;///tag
CNode *T=Root;
if(Root==NULL)
return;
CNode *p=T;
do
{
while(p!=NULL)
{
S1.push(p);
S2.push(0);
p=p->left;
}
if(S1.empty())
break;
if(p==NULL)
{
tag=S2.top();
if(tag==0)
{
tag=1;
S2.pop();
S2.push(tag);
p=S1.top()->right;
}
else if(tag==1)
{
p=S1.top();
S1.pop();
S2.pop();
cout<<p->data;
p=NULL;
}
}
}while(!S1.empty());
}
};
int main()
{
int T;
cin>>T;
while(T--)
{
string str;
cin>>str;
BiTree tree(str);
tree.nonPost();
cout<<endl;
}
return 0;
}