数据结构-非递归实现后序遍历二叉树

最近在看关于树结构方面的东西,想着实现二叉树的遍历操作。层序,先序,中序都还好,后序就比较麻烦,下面的地址很好的解释了递归与非递归的实现方法,在此给出另一种非递归实现后序遍历二叉树的方法,通过复杂化数据结构,使得算法更简单。

http://blog.csdn.net/pi9nc/article/details/13008511

#include"iostream"
#include "stack"
using namespace std;
#define N 7

typedef struct node
{
	struct node* leftchild;
	struct node* rightchild;
	struct node* parent;
	int data;
	int flag;
}BiTreeNode, *bt;

BiTreeNode* CreateNode(int data)
{
	BiTreeNode* t=new BiTreeNode;
	t->data=data;
	t->leftchild=NULL;
	t->rightchild=NULL;
	t->flag=0;
	return t;
}

bt CreateBiTree()
{
	bt p[N]={NULL};
	for(int i=0;i<N;i++)
	{
		p[i]=CreateNode(i+1);
	}
	for(int i=0;i<N/2;i++)
	{
		p[i]->leftchild=p[2*i+1];
		p[i]->rightchild=p[2*i+2];
	}

	for(int i=0;i<N;i++)
	{
		if(i==0)
			p[i]->parent=NULL;
		else if(i%2==0)
			p[i]->parent=p[i/2-1];
		else
			p[i]->parent=p[(i+1-1)/2];
	}
	return p[0];
}

int max(int a,int b)
{
	return a>b?a:b;
}
int depth(bt t)
{
	if(t==NULL)return 0;
	int nLeftDepth=depth(t->leftchild);
	int nRightDepth=depth(t->rightchild);

	return 1+max(nLeftDepth,nRightDepth);
	
}
//层序遍历
void PrintNodeByOrder(bt b,int level)
{
	if(b==NULL || level<1)
		return;
	if(1 == level)
	{
		cout<<b->data<<"  ";
		return;
	}
	PrintNodeByOrder(b->leftchild,level-1);
	PrintNodeByOrder(b->rightchild,level-1);
}
void LevelTraverse(bt b)
{
	int nHeight=depth(b);
	if(nHeight==0)
		cout<<"树为空"<<endl;
	for(int i=1;i<=nHeight;i++)
	{
		PrintNodeByOrder(b,i);
		cout<<endl;
	}
}

//先序非递归遍历
void PreTraverse(bt t)
{
	stack<bt>c;
	bt q=t;
	while(q!=NULL || !c.empty())
	{
		while(q!=NULL)
		{
			cout<<q->data;
			c.push(q);
			q=q->leftchild;
		}
		if(!c.empty())
		{
			q=c.top();
			c.pop();
			q=q->rightchild;
		}
	}
}

//中序非递归遍历
void InTraverse(bt t)
{
	stack<bt>c;
	bt q=t;
	while(q!=NULL || !c.empty())
	{
		while(q!=NULL)
		{
			c.push(q);
			q=q->leftchild;
			
		}
		
		if(!c.empty())
		{
			q=c.top();
			cout<<q->data;
			c.pop();
			q=q->rightchild;
		}
	}
}

//后序非递归遍历
void PostOrder(bt t)
{
	bt m=t;
	while(m!=NULL)
	{
		switch(m->flag)
		{
			case 0:
				{
					m->flag=1;
					if(m->leftchild!=NULL)
						m=m->leftchild;
					break;
				}
			case 1:
				{
					m->flag=2;
					if(m->rightchild!=NULL)
						m=m->rightchild;
					break;
				}
			case 2:
				{
					m->flag=0;
					cout<<m->data;
					m=m->parent;
					break;
				}
		}
	}
}
int main()
{
	BiTreeNode* p=CreateBiTree();

	cout<<"层次遍历"<<endl;
	LevelTraverse(p);
	cout<<endl;

	cout<<"先序非递归遍历"<<endl;
	PreTraverse(p);
	cout<<endl;

	cout<<"中序非递归遍历"<<endl;
	InTraverse(p);
	cout<<endl;

	cout<<"后序非递归遍历"<<endl;
	PostOrder(p);
	cout<<endl;
	return 0;
}

程序亲测可用。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值