ZOJ 3170 7 Levels of Binary Search Tree

题目很简单,主要是建树要思考下.

我用的是队列,按层次来建的.

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <memory.h>
#include <queue>
using namespace std;
const int maxn = 130;
int treVal[maxn], tree[maxn];
int n, L;
struct node{
	int idx, cnt, l, r; //结点索引值, 结点的子节点数量, 排序后的数组的两个范围.
	node(int ii = 0, int cc = 0, int ll = 0,int rr = 0):idx(ii), cnt(cc), l(ll), r(rr){}
};
void buildTree(){
	queue<node> q;
	q.push(node(1, n - 1, 1, n));
	while (q.size()){//广度优先建树
		node t = q.front(); q.pop();
		int idx = t.idx, cnt = t.cnt, l = t.l, r = t.r;
		if(cnt > 0){
			int lcnt = 0, rcnt = 0;
			scanf("%d", &lcnt), scanf("%d", &rcnt);
			if(lcnt > 0){
				q.push(node(idx << 1, lcnt - 1, l, l + lcnt - 1));
			}
			if(rcnt > 0){
				q.push(node(idx << 1 | 1, rcnt - 1, l + lcnt + 1, r));
			}
			tree[idx] = treVal[l + lcnt];
		}else{
			tree[idx] = treVal[l];
		}
	}

}

void postOrder(int idx,int & c){
	if(tree[idx] >= 0){
		postOrder(idx << 1, c);
		postOrder(idx << 1 | 1, c);
		if(c++ > 0 )printf(" ");
		printf("%d",tree[idx]);
	}
}
int main(){
	while (~scanf("%d", &n)){
		memset(tree, -1, sizeof(tree));
		for (int i = 1; i <= n; ++i){
			scanf("%d", &treVal[i]);
		}
		sort(treVal + 1, treVal + n + 1);
		scanf("%d", &L);
		buildTree();
		int c = 0;
		postOrder(1, c);
		printf("\n");
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值