PAT|1147 Heaps(最大堆、最小堆、二叉树的遍历)

题目大意

在计算机科学中,堆是一种特殊的基于树的数据结构,它满足堆属性:如果 P 是 C 的父节点,则 P 的键(值)要么大于或等于(在最大堆中) ) 或小于或等于(在最小堆中)C 的键。堆的常见实现是二叉堆,其中树是完全二叉树。 (引自维基百科 https://en.wikipedia.org/wiki/Heap_(data_structure)) 你的工作是判断一个给定的完整二叉树是否是一个堆。

解题分析

  • 首先需要明白最大、最小堆的定义
  • 根据完全二叉树可以由下标计算出孩子节点的下标,进而访问
  • 最后进行后序遍历即可

代码

#include<bits/stdc++.h>
using namespace std;
int n, m;
bool minheep, maxheep;
vector<int> vec;
vector<int> post;
void judgeMaxHeep(int index) {
	if (index * 2 <= m) {//存在左节点
		if (vec[index] < vec[index * 2]) {
			maxheep = false;
		}
		else {
			judgeMaxHeep(index * 2);
		}		
	}
	if (index * 2 + 1 <= m) {//存在右节点
		if (vec[index] < vec [index * 2 + 1]) {
			maxheep = false;
		}
		else {
			judgeMaxHeep(index * 2 + 1);
		}
	}
}
void judgeMinHeep(int index) {
	if (index * 2 <= m) {//存在左节点
		if (vec[index] > vec[index * 2]) {
			minheep = false;
		}
		else {
			judgeMinHeep(index * 2);
		}
	}
	if (index * 2 + 1 <= m) {//存在右节点
		if (vec[index] > vec[index * 2 + 1]) {
			minheep = false;
		}
		else {
			judgeMinHeep(index * 2 + 1);
		}
	}
}
void postorder(int index) {
	if (index * 2 <= m) {
		postorder(index * 2);
	}
	if (index * 2 + 1 <= m) {
		postorder(index * 2 + 1);
	}
	post.push_back(vec[index]);
}
void printPost() {
	if (post.size() >= 1) {
		cout << post[0];
	}
	for (int i = 1; i < m; i++) {
		cout << ' ' << post[i];
	}
	cout << endl;
}
int main() {
	//根据层次遍历判断是否为最大或者最小堆
	cin >> n >> m;
	vec.resize(m + 1);
	for (int i = 0; i < n; i++) {
		for (int j = 1; j <= m; j++) {
			cin >> vec[j];
		}
		minheep = maxheep = true;
		judgeMaxHeep(1);
		judgeMinHeep(1);
		if (maxheep == true) {
			cout << "Max Heap" << endl;
		}
		else if (minheep == true) {
			cout << "Min Heap" << endl;
		}
		else {
			cout << "Not Heap" << endl;
		}
		post.clear();
		postorder(1);
		printPost();
	}

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值