二叉树后序遍历算法

来源:互联网 发布:阿里云域名备案 编辑:程序博客网 时间:2024/06/13 20:24

二叉树后序遍历算法


#include <iostream>
//#include <climits>
using namespace std;


#define  MAXNUM 50
typedef int Elemtype;
typedef struct BiTNode 
{
Elemtype data;
struct BiTNode *lchild;
struct BiTNode *rchild;
}BiTNode,*BiTree;


typedef struct
{
BiTree bt;
int tag;       // 标签
}Elem;


typedef struct sqStack         //  栈
{
Elem s_elem[MAXNUM];       
int top;
}sqStack;


void InitStack(sqStack &s)      //  初始化栈
{
s.top=-1;
}
bool IsEmpty(sqStack s)      //  判断栈是否为空
{
if (s.top==-1)
return true;
else
return false;
}


bool Push(sqStack &s,Elem e)            //  进栈
{
if ((s.top+1)==MAXNUM)   //  栈满    
return false;
s.s_elem[++s.top]=e;
return true;
}


bool Pop(sqStack &s,Elem &e)            //  出栈
{
if (s.top==-1)   //  栈满    
return false;
e=s.s_elem[s.top--];
return true;
}


bool GetTop(sqStack s,Elem &e)         //  获取栈顶元素
{
if (s.top==-1)   //  栈满    
return false;
e=s.s_elem[s.top];
return true;
}
void CreateBiTree(BiTree &T)
{
Elemtype data;
scanf("%d",&data);


if(data!=99)
{
T=new BiTNode;
T->data=data;
T->lchild=NULL;
T->rchild=NULL;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}

void PostOrder(BiTree T)     //  二叉树非递归后序遍历
{
sqStack s;


InitStack(s);
BiTNode *p=T;     //  指向头结点
do 
{
while (p)
{
Elem et;
et.bt=p;
et.tag=1;
Push(s,et);
p=p->lchild;        //  将左孩子全部进栈
}
if (!IsEmpty(s))
{
Elem ee;
Pop(s,ee);            
if (ee.tag==1){
ee.tag=2;
p=ee.bt->rchild;
Push(s,ee);

else{
cout<<ee.bt->data<<"  ";
}
}
} while (!IsEmpty(s));
}

0 0
原创粉丝点击