L2-006 树的遍历 (建树)

思路:

        我们都知道,一颗二叉树,给定中序序列和任意其它序列,可以建造出整颗二叉树。树的建造有两种方式,一种是静态,一种是动态。

AC 代码(动态):

#include<bits/stdc++.h>
using namespace std;
const int N = 100,INF = 0x3f3f3f3f;
struct Tree {
	int val;
	Tree *l = NULL;
	Tree *r = NULL;
	Tree(int x) {
		val = x;
	}
}*root;
int n,a[N],b[N],len;
int ans[N];
void builtTree(int l,int r,int &t,Tree *&root) {
	int pos = -1;
	for(int i = l; i <= r; i ++) {
		if(a[t] == b[i]) {
			pos = i;
			break;
		}
	}
	if(pos == -1) return ;
	root = new Tree(b[pos]);
	t --;
	if(pos < r) {
		builtTree(pos + 1,r,t,root->r);
	}
	if(l < pos) {
		builtTree(l,pos - 1,t,root->l);
	}
}
void bfs() {
	queue<Tree*> q;
	q.push(root);
	while(!q.empty()) {
		Tree* tmp = q.front();
		q.pop();
		ans[len ++] = tmp->val;
		if(tmp->l != NULL)
			q.push(tmp->l);
		if(tmp->r != NULL)
			q.push(tmp->r);
	}
}
int main() {
	cin>>n;
	for(int i = 1; i <= n; i ++) {
		cin>>a[i];
	}
	for(int j = 1; j <= n; j ++) {
		cin>>b[j];
	}
	builtTree(1,n,n,root);
	bfs();
	for(int i = 0; i < len; i ++) {
		if(i == len - 1)
			cout<<ans[i];
		else cout<<ans[i]<<" ";
	}
	return 0;
}

AC 代码(静态):

        这中按完全二叉树建树的方式很费空间,最好不要按这种方式设置左右子树,但是这道题数据范围小,可以用。

#include<bits/stdc++.h>
using namespace std;
const int N = 10000,INF = 0x3f3f3f3f;
struct Tree {
	int val;
	int l,r;
}tree[N];
int n,a[N],b[N],len;
int ans[N];
void builtTree(int l,int r,int &t,int idx) {
	int pos = -1;
	for(int i = l; i <= r; i ++) {
		if(a[t] == b[i]) {
			pos = i;
			break;
		}
	}
	if(pos == -1) return ;
	tree[idx].val = b[pos];
	tree[idx].l = 2 * idx;
	tree[idx].r = 2 * idx + 1;
	t --;
	if(pos < r) {
		builtTree(pos + 1,r,t,2*idx+1);
	}
	if(l < pos) {
		builtTree(l,pos - 1,t,2*idx);
	}
}
void bfs() {
	queue<Tree> q;
	q.push(tree[1]);
	while(!q.empty()) {
		Tree tmp = q.front();
		q.pop();
		ans[len ++] = tmp.val;
		if(tree[tmp.l].val != 0)
			q.push(tree[tmp.l]);
		if(tree[tmp.r].val != 0)
			q.push(tree[tmp.r]);
	}
}
int main() {
	cin>>n;
	for(int i = 1; i <= n; i ++) {
		cin>>a[i];
	}
	for(int j = 1; j <= n; j ++) {
		cin>>b[j];
	}
	builtTree(1,n,n,1);
	bfs();
	for(int i = 0; i < len; i ++) {
		if(i == len - 1)
			cout<<ans[i];
		else cout<<ans[i]<<" ";
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值