上机四:二叉树的建立和前中后序遍历

上机四

建立一棵二叉树并实现前中后序的遍历

内容要求

前序和后序使用递归遍历
中序非递归遍历

代码

#include<iostream>//上机4:二叉树的建立和前中后序遍历
using namespace std;
class node
{
public:
	char data;
	node *left;
	node *right;
};
class tree
{
private:
	node *root;
	int top;
	node *s[100];//顺序栈
	node *creat(node *t)//构造函数调用
	{
		char ch;
		cin>>ch;
		if(ch=='#')t=NULL;
		else
		{
			t=new node;
			t->data=ch;
			t->left=creat(t->left);
			t->right=creat(t->right);
		}
		return t;
	}
	void del(node *t)//析构函数调用
	{
		if(t!=NULL)
		{
			del(t->left);
			del(t->right);
			delete t;
		}
	}
	void pre(node *t)//前序递归遍历
	{
		if(t==NULL)return ;
		else
		{
			cout<<t->data<<' ';
			pre(t->left);
			pre(t->right);
		}
	}
	void post(node *t)//后序递归
	{
		if(t==NULL)return ;
		else
		{
			post(t->left);
			post(t->right);
			cout<<t->data<<' ';
		}
	}
	void in(node *t)//中序非递归遍历
	{
		top=-1;
		while(t!=NULL||top!=-1)
		{
			while(t!=NULL)
			{
				s[++top]=t;
				t=t->left;
			}
			if(top!=-1)
			{
				t=s[top--];
				cout<<t->data<<' ';
				t=t->right;
			}
		}
	}
public:
	void creat(){root=creat(root);}//建立树
	~tree(){del(root);}//析构函数
	void pre(){pre(root);}//前序遍历
	void in(){in(root);}//中序遍历
	void post(){post(root);}//后序遍历
};
int main()
{
	tree a;
	cout<<"1建树,2前序递归,3中序非递归,4后序递归,0退出"<<endl;
	cout<<"请选择操作:";
	int n;
	cin>>n;
	while(n)
	{
		
		switch(n)
		{
		case 1:
			cout<<"请输入结点元素,根->左子树->右子树,输#置空"<<endl;
			a.creat();break;
		case 2:a.pre();break;
		case 3:a.in();break;
		case 4:a.post();break;
		}
		cout<<endl;
		cout<<"请选择操作:";
		cin>>n;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

纸梯先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值