1147 Heaps (30 分)

PAT1147
题意,给出m个完全二叉树的层序遍历,树的结点时固定n个,要求判断是Min_Heap or Max_Heap or Not_Heap;
这个题目简单,用树的后序遍历,判断根是否大于左右儿子
需要注意的是,叶子结点的处理,那么如果判断max_heap 则将不存在的结点当作无穷小即一个很大的负数(因为题目说是integer) 我开始用的0,挂3个点,原来题目说的是整数,那么最小值不用用0了。 如果判断min_heap 不存在的结点看作无穷大就好了。
还学习了一个完全二叉树以0为根节点的存储方式
0为根 1 左子树 2右子树
则 左子树为root2 + 1 右子树为 root2 + 2;
左子树的根为(l-1)
2 右子树的根为(r-1)2;

1为根 2 左子树 3右子树
则 左子树为root2 右子树为 root2 + 1;
左子树的根为(l)
2 右子树的根为(r)2;

也就是算子节点少加一个1,算父节点少减一个

则这题的judge 就可以简化为一个for循环 从第二个结点开始判断它是否大于 或者 小于 它的根结点了。O(n - 1)的时间复杂度,但是思路更清晰了。

bool ismax()
{
    for(int i = 1; i < n; i++)
        if(tree[i] > tree[(i - 1) / 2])
            return false;
    return true;
}
bool ismin()
{
    for(int i = 1; i < n; i++)
        if(tree[i] < tree[(i - 1) / 2])
            return false;
    return true;
}
#include<bits/stdc++.h>
using namespace std;
const int N = 1010;
int tree[N];
int n;
int nums;
bool judge_min(int root) {
	if(root > n) return true;
	int l = 0x7fffffff, r = 0x7fffffff; //不存在的结点默认值
	bool flag = false;
	if(root*2 <= n) r = tree[root*2];
	if(root*2 + 1 <= n) l = tree[root*2 + 1];
	if(tree[root] <= r && tree[root] <= l) flag = true;
	return flag && judge_min(root*2) &&  judge_min(root*2 + 1); //左子树 右子树 都满足 并且 自己也满足
}

bool judge_max(int root) {
	if(root > n) return true;
	int l = -1000000, r = -1000000; //不存在的结点默认值
	bool flag = false; 
	if(root*2 <= n) l = tree[root*2];
	if(root*2 + 1 <= n) r = tree[root*2 + 1];
	if(tree[root] >= l && tree[root] >= r) flag = true;
	return flag && judge_max(root*2) && judge_max(root*2 + 1);
}

void print_post_order(int root) {
	if(root > n) return ;
	print_post_order(root*2);
	print_post_order(root*2 + 1);
	printf("%d%c", tree[root], ++nums < n ? ' ' : '\n'); 
}

int main() {
	int query;
	scanf("%d %d", &query, &n);
	while(query--) {
		for(int i = 1; i <= n; i++) {
			scanf("%d", &tree[i]);
		}
		nums = 0;
		bool is_min = judge_min(1);
		bool is_max = judge_max(1);
		if(!is_min && !is_max) {
			printf("Not Heap\n");
		} else {
			printf("%s Heap\n", is_max == true ? "Max" : "Min"); 
		}
		print_post_order(1);
	}
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值