PAT甲级A1155 Heap Paths (30 分)

In computer science, a heap is a specialized tree-based data structure that satisfies the heap property: if P is a parent node of C, then the key (the value) of P is either greater than or equal to (in a max heap) or less than or equal to (in a min heap) the key of C. A common implementation of a heap is the binary heap, in which the tree is a complete binary tree. (Quoted from Wikipedia at https://en.wikipedia.org/wiki/Heap_(data_structure))

One thing for sure is that all the keys along any path from the root to a leaf in a max/min heap must be in non-increasing/non-decreasing order.

Your job is to check every path in a given complete binary tree, in order to tell if it is a heap or not.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (1int), which gives the level order traversal sequence of a complete binary tree.

Output Specification:

For each given tree, first print all the paths from the root to the leaves. Each path occupies a line, with all the numbers separated by a space, and no extra space at the beginning or the end of the line. The paths must be printed in the following order: for each node in the tree, all the paths in its right subtree must be printed before those in its left subtree.

Finally print in a line Max Heap if it is a max heap, or Min Heap for a min heap, or Not Heap if it is not a heap at all.

Sample Input 1:

8
98 72 86 60 65 12 23 50

Sample Output 1:

98 86 23
98 86 12
98 72 65
98 72 60 50
Max Heap

Sample Input 2:

8
8 38 25 58 52 82 70 60

Sample Output 2:

8 25 70
8 25 82
8 38 52
8 38 58 60
Min Heap

Sample Input 3:

8
10 28 15 12 34 9 8 56

Sample Output 3:

10 15 8
10 15 9
10 28 34
10 28 12 56
Not Heap

题意:给出一个完全二叉树的层序序列,首先让你输出所有从根节点到叶节点的路径,但要求先输出右子树的路径,再输出左子树的路径。接下来让你判断这棵二叉树是大顶堆还是小顶堆,或者不是堆并输出对应判断结果。 

思路:使用数组存储这可完全二叉树,则下标之间有如下关系,设当前结点下标i,则左孩子为2*i+1,右孩子为2*i+2,根据下表之间的对应关系,对这棵树执行DFS,但左右子树的访问顺序颠倒一下,然后使用vectorpath存储路径上的节点,每次碰到叶结点(下标>=n/2)就输出path,最终遍历结束就能输出所有从根节点到叶节点的路径。

接下来判断这可完全二叉树是否是堆。对于大顶堆,所有节点满足当前结点小于等于父节点这也性质,如果对于除根节点以外的所有节点都有这一性质,则为大顶堆,小顶堆相反。如果两个都不满足则不是堆。

参考代码:

#include
#include
using namespace std;
int n,Heap[1010];
vector path;
int judge(){
	int flag=1;
	for(int i=n-1;i>0&&flag;i--){	//判断大顶堆
		if(Heap[i]>Heap[(i-1)/2])
			flag=0;
	}
	if(flag) return 1;
	flag=1;
	for(int i=n-1;i>0&&flag;i--){	//判断小顶堆
		if(Heap[i]=n) return;
	path.push_back(Heap[root]);
	if(root>=n/2){
		for(int i=0;i

 

你可能感兴趣的:(PAT甲级,递归,堆,DFS和BFS)