Computer four: Binary tree establishment and traversal in front, middle and back [Pi Pilei]

Machine Four

Build a binary tree and realize the traversal of the first, middle and last order

Content requirements

Pre-order and post-order use recursive traversal
, middle-order non-recursive traversal

Code

#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;
	}
}

Guess you like

Origin blog.csdn.net/qq_43704702/article/details/104029541