PAT - L2 - 011 玩转二叉树(分治)

本文介绍了一种通过递归算法构建树形结构的方法。利用两个数组a和b分别表示树的前序遍历和中序遍历,实现了树的构建过程,并通过队列实现了树的层次遍历打印。需要注意的是,在实验中发现最大节点数至少要设置为49才能通过测试。

 

思路:将整棵树划分成 n 个子树

坑点:maxn 最小取 49 (我也不知道为啥,题目明明是 n<30)

 

代码如下:

#include<bits/stdc++.h>
using namespace std;

const int maxn = 50; // 试了几次,发现最小取 49,可以过
int a[maxn],b[maxn];
struct node{
	int l,r;
}tree[maxn];

int build(int x1,int y1,int x2,int y2){
	if(x1>y1) return 0;
	int k=x1;
	while(a[k]!=b[x2]) k++;
	tree[b[x2]].l = build(x1,k-1,x2+1,x2+k-x1);
	tree[b[x2]].r = build(k+1,y1,x2+1+k-x1,y2);
	return b[x2];
}

void print(int o){
	int k=0;
	queue<int> q;
	q.push(o);
	while(q.empty()==0){
		int x=q.front();
		if(k==0){
			cout << x;
			k=1;
		}
		else cout << ' ' << x;
		q.pop();
		if(tree[x].r!=0) q.push(tree[x].r);
		if(tree[x].l!=0) q.push(tree[x].l);
	}
	cout << endl;
	return;
}

int main()
{
	int n;
	cin >> n;
	for(int i=0; i<n; i++)
		cin >> a[i];
	for(int i=0; i<n; i++)
		cin >> b[i];	
	int o=build(0,n-1,0,n-1);	
	print(o);	
	return 0;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值