1086 Tree Traversals Again (25分)(由前序+中序求后序)

之前建树都是用数组存储,这回用指针

#include<bits/stdc++.h>
#define ll long long
#define inf 999999999
using namespace std;
int qian[50];
int zhong[50];
vector<int> v;
struct node{
	int data;
	node* left;   //java里面的"指针"就是直接不加星号即可
	node* right;
};
node* build(int l1,int r1,int l2,int r2)
{
	if(l1>r1) 
		return NULL; //结束时就返回空
	node* root=new node; //开一个node,用来存储根节点,左儿子,右儿子
	root->data=qian[l1];
	int p=l2;
	while(zhong[p]!=root->data)
		p++;
	int cnt=p-l2;
	root->left=build(l1+1,l1+cnt,l2,l2+cnt-1);
	root->right=build(l1+cnt+1,r1,p+1,r2);
	return root;
}
void houshow(node* root)
{
	if(root==NULL)
		return;
	houshow(root->left);
	houshow(root->right);
	v.push_back(root->data);
}
int main()
{
	int n;
	cin>>n;
	stack<int> s;
	string t;
	int a,k1=0,k2=0;
	for(int i=1;i<=2*n;i++)
	{
		cin>>t;
		if(t=="Push")
		{
			cin>>a;
			qian[k1++]=a;	
			s.push(a);
		}
		else
		{
			zhong[k2++]=s.top();
			s.pop();
		}	
	}
	node* root=build(0,n-1,0,n-1);
	houshow(root); 
	for(int i=0;i<v.size()-1;i++)
		cout<<v[i]<<" ";
	cout<<v[v.size()-1]<<endl;
} 

求层序遍历

void bfs(node* root)
{
	queue<node*> q; //注意这里村的是指针类型
	q.push(root);
	while(!q.empty())
	{
		node* u=q.front();
		q.pop();
		v.push_back(u->data);
		if(u->l!=NULL)
			q.push(u->l);
		if(u->r!=NULL)
			q.push(u->r);
	}
}

附上用数组的写法:

#include<bits/stdc++.h>
#define ll long long
#define inf 999999999
using namespace std;
int qian[105];
int zhong[105];
struct node{
	int left;
	int right;
}tree[100005]; //有的题数特别大的话就不能用数组写法
vector<int> v;
int build(int l1,int r1,int l2,int r2)
{
	if(l1>r1)
		return -1;
	int root=qian[l1];
	int p=l2;
	while(zhong[p]!=root)
		p++;
	int cnt=p-l2;
	tree[root].left=build(l1+1,l1+cnt,l2,l2+cnt-1);
	tree[root].right=build(l1+cnt+1,r1,p+1,r2);
	return root;
}
void houshow(int root)
{
	if(root==-1)
		return;
	houshow(tree[root].left);
	houshow(tree[root].right);
	v.push_back(root);
}
int main()
{
	int n;
	cin>>n;
	stack<int> s;
	string t;
	int a,k1=0,k2=0;
	for(int i=1;i<=2*n;i++)
	{
		cin>>t;
		if(t=="Push")
		{
			cin>>a;
			s.push(a);
			qian[k1++]=a;
		}
		else
		{
			zhong[k2++]=s.top();
			s.pop();
		}	
	}
	int root=build(0,n-1,0,n-1);
	houshow(root); 
	for(int i=0;i<v.size()-1;i++)
		cout<<v[i]<<" ";
	cout<<v[v.size()-1]<<endl;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

henulmh

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

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

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

打赏作者

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

抵扣说明:

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

余额充值