天天看點

棧 實作中序後序先序周遊二叉樹

#include<iostream>
#include<stack>
#include<fstream>   
#include<time.h>
using namespace std;

ofstream out1("diguixianxu.txt");
ofstream out2("zhanxianxu.txt");
struct node
{
	int num;
	int times;
	node* l,* r;
	node(int e)
	{num=e; times=1; l=r=NULL;}
};

void build(node*&p,int e)
{
	if(p==NULL)
	{
		p=new node(e);
		return;
	}
	if(e<p->num)
		build(p->l,e);
		
	else
		build(p->r,e);
	
}

void init(node*&head)
{
	head=new node(100);

	for(int i=0;i<500;i++)
	{
		int num=rand()%600;

		build(head,num);
	}

	cout<<"\n\n";
}

void first(node* p)
{

	if(p==NULL)
		return;	
	out1<<p->num<<" ";
	cout<<p->num<<" ";
	first(p->l);

	first(p->r);
}

void stackfirst(node* p)
{
	node* tem;
	stack<node*>s;
	s.push(p);
	while(!s.empty())
	{
		while((tem=s.top())&&tem)
		{
			out2<<tem->num<<" ";
			cout<<tem->num<<" ";
			s.push(tem->l);
		}
		s.pop();
        if(!s.empty())
		{
			tem=s.top();
			s.pop();
			s.push(tem->r);
		}
	}

}

void mid(node* p)
{
	if(p==NULL)
		return;
	mid(p->l);	
	out1<<p->num<<" ";
	cout<<p->num<<" ";
	mid(p->r);
}




void stackmid(node* p)
{
	node* tem;
	stack<node*>s;
	s.push(p);
	while(!s.empty())
	{
		while((tem=s.top())&&tem)
			s.push(tem->l);
		s.pop();
        if(!s.empty())
		{
			tem=s.top();
			out2<<tem->num<<" ";
			cout<<tem->num<<" ";
			s.pop();
			s.push(tem->r);
		}
	}

}



void last(node* p)
{
	if(p==NULL)
		return;
	last(p->l);	
	last(p->r);
	out1<<p->num<<" ";
    cout<<p->num<<" ";
}

void stacklast(node* p)
{
	node* tem;
	stack<node*>s;
	s.push(p);
	while(!s.empty())
	{
		while((tem=s.top())&&tem)
			s.push(tem->l);
		s.pop();
        if(!s.empty())
		{
			tem=s.top();
			if(tem->times==1)
			{
				(tem->times)++;	
				s.push(tem->r);
			}
			else
			{	cout<<tem->num<<" ";
				out2<<tem->num<<" ";
				s.pop();
				s.push(NULL);
			}
		
		}
	}

}
void del(node* p)
{
	if(p==NULL)
		return;
	del(p->l);
	del(p->r);
	delete p;
}
int main()
{
	srand(time(0));
		node* head;

		init(head);

		first(head);
		cout<<"\n";
		stackfirst(head);
		

	
		mid(head); 
		cout<<"\n";
		stackmid(head);
	
		last(head);
		cout<<"\n";
		stacklast(head);

		del(head);

out1.close();
out2.close();

}
           
c++

繼續閱讀