二叉树的前序,中序,后序遍历。用递归和非递归实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Dongfnag_HU/article/details/77103129
#include<iostream>
#include<stack>
using namespace std;

#define MAX 100

typedef struct Tree{
	int data;
	Tree*lchild;
	Tree*rchild;
}*TREE,NODE;

int i;//定义全局变量

void Enter(TREE&t,int a[]);
void Init(TREE &t);
void Display_pre(TREE t);
void Display_Pre(TREE t);
void Display_mid(TREE t);
void Display_Mid(TREE t);
void Display_las(TREE t);
void Display_Las(TREE t);
int main()
{
	TREE T=NULL;
	
	Init(T);
	Display_pre(T);cout<<endl;Display_Pre(T);cout<<endl<<endl;
	Display_mid(T);cout<<endl;
	Display_las(T);cout<<endl;Display_Las(T);cout<<endl;
	
	
	return 0;
}

void Enter(TREE&t,int a[]) //Init()的辅助函数,完成递归创建 
{
	static int j=0;
	if(a[j++])
	{
		t=new NODE;
		t->data=a[j-1];
		t->lchild=t->rchild=NULL;
		
		Enter(t->lchild,a);
		Enter(t->rchild,a);
	}
	else
	t=NULL;
}

void Init(TREE &t)
{
	int a[MAX];
	FILE*fp;
	fp=fopen("C:\\Users\\Administrator\\Desktop\\asd.txt","r");
	
	i=0;
	while(!feof(fp))             //将内容读取到数组中 
	 fscanf(fp,"%d",&a[i++]);    
	 
	 Enter(t,a);
	 
	 cout<<"Initialize sucessfully!"<<endl;
}

void Display_pre(TREE t)
{
	if(t)
	{cout<<t->data<<' ';
	Display_pre(t->lchild);
	Display_pre(t->rchild);
	}
}

void Display_mid(TREE t)
{
	if(t)
	{
		Display_mid(t->lchild);
		cout<<t->data<<' ';
		Display_mid(t->rchild);
	}
}

void Display_las(TREE t)
{
	if(t)
	{
		Display_las(t->lchild);
		Display_las(t->rchild);
		cout<<t->data<<' ';
	}
}

void Display_Pre(TREE t)
{
	if(!t)                       
	{
		cout<<"NULL!"<<endl;
		return;
	}
	
	TREE temp=t;
	stack<TREE> s;
	
	while((temp!=NULL)||!s.empty())
	{
		while(temp)
		{
			cout<<temp->data<<' ';
		    s.push(temp);
		    temp=temp->lchild;
		}
		
		if(!s.empty())
		{
			temp=s.top();
			s.pop();
			temp=temp->rchild;
		}
	}
}

void Display_Mid(TREE t)
{
	if(t==NULL)
	{
		cout<<"NULL!"<<endl;
		return;
	}
	
	TREE temp=t;
	stack<TREE> s;
	
	while((temp!=NULL)||!s.empty())
	{
		while(temp)
		{
			s.push(temp);
			temp=temp->lchild;
		}
		
	    if(!s.empty())
	    {
	    	temp=s.top();
	    	cout<<temp->data;
	    	s.pop();
	    	temp=temp->rchild;
		}
		
	}
}

void Display_Las(TREE t)
{
   if(!t)
   {
    cout<<"NULL!"<<endl;
    return;
   }
   
   TREE temp=t,temp_past=NULL;//temp为当前访问的节点,temp_past为上一个访问的节点 
   stack<TREE>s;
   
   while(temp)   //移动到最底部左子树 
   {
   	 s.push(temp);
   	 temp=temp->lchild;
   }
   
   while(!s.empty())
   {
   	  temp=s.top();
   	  s.pop();
   	  
   	  if((temp->rchild==NULL)||(temp_past==temp->rchild)) //输出一个根节点的条件就是其右子树为空,或者其右子树已经被访问 
   	  {
   	  	cout<<temp->data<<' ';
   	  	temp_past=temp;
	  }
	  else
	  {
	  	s.push(temp);          //二次入栈 
	  	temp=temp->rchild;     //进入右子树 
	  	
	  	while(temp)
	  	{
	  		s.push(temp);
	  		temp=temp->lchild;
		}
	  }
   }
   
}

猜你喜欢

转载自blog.csdn.net/Dongfnag_HU/article/details/77103129