栈 实现中序后序先序遍历二叉树

#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();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值