二叉树的非递归遍历

建立二叉链表存储结构,创建二叉树。利用栈实现非递归中序遍历。

输入序列为:1 2 0 4 0 0 3 5 0 0 0 

#include<stdio.h>
#include<iostream>
#include<malloc.h>
#define TRUE 1
#define FALSE 0
#define ok 1
#define maxsize 100
using namespace std;
typedef struct binode
{
	int data;
	struct binode *lchild,*rchild;
}binode,*bitree;
typedef struct 
{
	binode *a[maxsize];
	int top;
}sqstack;
int treecreated=FALSE;
int creatbitree(bitree *T);
void nrinordertraverse(bitree T);
void push(sqstack *s,binode *x);
binode *pop(sqstack *s);

void main()
{
	int choice=0,flag;
	int leave=FALSE;
	binode * BT;
	cout<<"========利用栈实现非递归遍历演示程序=========="<<endl;
	do
	{
		cout<<"1.创建一个二叉树,按先序遍历结果输入,空用0表示"<<endl;
		cout<<"2.中序遍历二叉树,非递归方式遍历二叉树"<<endl;
		cout<<"0.quit"<<endl;
		cout<<"-----input your selection:";
		cin>>choice;
		switch(choice)
		{
		case 1:
			if(treecreated)
			{
				cout<<"sorry,the tree has been already created!"<<endl;
				break;
			}
			cout<<"please put in number!"<<endl;
			flag=creatbitree(&BT);
			if(flag==ok)
			{
				cout<<"okey,now a tree named BT is created.."<<endl;
				treecreated=TRUE;
			}
		case 2:
			cout<<"in nrorder:";
			nrinordertraverse(BT);
			cout<<endl;
			break;
		case 0:
			leave=TRUE;
			break;
		}
	}while(!leave);
		cout<<"thanks for using ,bye~"<<endl;
}
int creatbitree(bitree *T)
{
	int ch=0;
	cin>>ch;
	if(ch==0)
		(*T)=NULL;
	else
	{
		(*T)=(bitree)malloc(sizeof(binode));
		(*T)->data=ch;
		creatbitree(&(*T)->lchild);
		creatbitree(&(*T)->rchild);
	}
	return ok;
}
void nrinordertraverse(bitree T)
{
	sqstack s;
	binode *p;
	s.top=0;
	push(&s,T);
	while(s.top!=0)
	{
		while(s.a[s.top]!=NULL)
		{
			p=s.a[s.top];
			push(&s,p->lchild);
		}
		p=pop(&s);
		if(s.top!=0)
		{
			p=pop(&s);
			cout<<p->data<<"   ";
			push(&s,p->rchild);
		}
	}
	cout<<endl;
}
void push(sqstack *s,binode *x)
{
	if(s->top==maxsize)
		cout<<"stack overflow!"<<endl;
	else
	{
		s->top++;
		s->a[s->top]=x;
	}
}

binode *pop(sqstack *s)
{
	binode *x;
	if(s->top==0)
	{
		cout<<"stack underflow"<<endl;
		return(NULL);
	}
	else
	{
		x=s->a[s->top];
		s->top--;
		return(x);
	}
}


你可能感兴趣的:(二叉树的非递归遍历)