A1099

本题是由已知二叉树遍历得到中序遍历序列的逆用.
已知二叉树中序遍历序列,将每个结点的权重存入二叉树.
用数组存储,遍历过程与链表一致,由数组下标指向左右孩子代替链表指针指向左右孩子.
同类型题:A1064.

#include<cstdio>
#include<cstdlib>
#include<string.h>
#include<math.h>
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<string>
#include<algorithm>
using namespace std;
const int maxn=110;
int t[maxn],idx=0;
struct node{
	int data;
	int left_index;
	int right_index;
}nodes[maxn];
bool cmp(int a,int b){
	return a<b;
}
void inorder(int root){           //中序遍历
	if(root==-1){
		return;
	}
	inorder(nodes[root].left_index);
	nodes[root].data=t[idx++];
	inorder(nodes[root].right_index);
}
void levelorder(int root){         //层序遍历
	queue<int> q;
	q.push(root);
	while(!q.empty()){
		int now=q.front();
		q.pop();
		if(nodes[now].left_index!=-1){
			q.push(nodes[now].left_index);
		}
		if(nodes[now].right_index!=-1){
			q.push(nodes[now].right_index);
		}
		printf("%d",nodes[now].data);
		if(!q.empty()){
			printf(" ");
		}
	}
}
int main(){
	#ifdef ONLINE_JUDGE
	#else
		freopen("1.txt","r",stdin);
	#endif
	int n;
	scanf("%d",&n);
	for(int i=0;i<n;i++){
		scanf("%d %d",&nodes[i].left_index,&nodes[i].right_index);
	}
	for(int i=0;i<n;i++){
		scanf("%d",&t[i]);
	}
	sort(t,t+n,cmp);
	inorder(0);
	levelorder(0);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值