#include <stack>
#include <iostream>
using namespace std;
typedef struct BiTNode{
int data;
BiTNode *lchild, *rchild;
}BiTNode,*BiTree;
void CreateBiTree(BiTree &T)//建树,按先序顺序输入节点
{
int ch;
scanf("%d",&ch);
if(ch==0)
{
T=NULL;
return;
}
else
{
if(!T){
T = new BiTNode;
}
T->data=ch;
T->lchild = T->rchild =NULL;
cout<<T->data<<"的左子:"<<endl;
CreateBiTree((T->lchild));
cout<<T->data<<"右子:"<<endl;
CreateBiTree((T->rchild));
}
}
void myPostOrderTraverse(BiTree T){
int flag[20];
stack<BiTree> s;
if(!T)
{
printf("空树!\n");
return;
}
do{
while(T){
s.push(T); //3 6,7
T=T->lchild; //
flag[s.size()]=0;
}
while(!s.empty()&&flag[s.size()]==1){
T=s.top();
s.pop();
cout<<T->data<<endl;
}
if(!s.empty()){
T=s.top(); //1 6, 7
if(T->rchild==NULL){
cout<<T->data<<endl;
T=NULL;
s.pop();
}else{
flag[s.size()]=1;
T=T->rchild; //3 7
}
}
}while(!s.empty());//!s.empty()
}
int main()
{
BiTree T ;
CreateBiTree(T);
myPostOrderTraverse(T);
return 0;
}
学习笔记:二叉树后序遍历非递归算法
最新推荐文章于 2024-04-05 17:06:59 发布