1127 ZigZagging on a Tree (将层序遍历按z型输出, 2种方法,1.下标法构建满足题意的层序条件 2.构建树 BFS遍历层序)_树的层序zigzag输出,树按层序遍历,奇数层从左至右输出,偶数层从右至左输出。_月下独喝的博客-程序员宅基地

技术标签: pat甲级(树类型题)  

1127 ZigZagging on a Tree (30 分)

Suppose that all the keys in a binary tree are distinct positive integers. A unique binary tree can be determined by a given pair of postorder and inorder traversal sequences. And it is a simple standard routine to print the numbers in level-order. However, if you think the problem is too simple, then you are too naive. This time you are supposed to print the numbers in "zigzagging order" -- that is, starting from the root, print the numbers level-by-level, alternating between left to right and right to left. For example, for the following tree you must output: 1 11 5 8 17 12 20 15.

zigzag.jpg

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary tree. The second line gives the inorder sequence and the third line gives the postorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the zigzagging sequence of the tree in a line. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:

8
12 11 20 17 1 15 8 5
12 20 17 11 15 8 5 1

Sample Output:

1 11 5 8 17 12 20 15

/**
本题题意:
给出一颗树的后序,中序遍历(可以推导出先序遍历构建出唯一树),
输出此唯一树的层序遍历不过是z字型输出, eg: 第一层 从右往 左输出,第二层从左往右输出
方法一:本题思路
利用结点下标索引进行排序,先将高度排序,(根节点位于第0层)偶数层从右往左(从大到小排序,) 奇数层从左往右(从小到大排序)
**/

/**
本题题意:
给出一颗树的后序,中序遍历(可以推导出先序遍历构建出唯一树), 
输出此唯一树的层序遍历不过是z字型输出, eg: 第一层 从右往 左输出,第二层从左往右输出 
本题思路 
利用结点下标索引进行排序,先将高度排序,(根节点位于第0层)偶数层从右往左(从大到小排序,) 奇数层从左往右(从小到大排序) 
**/ 
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct Node{
	int h, index, data;	   // 
};
int n;
vector<int> post, in;
vector<Node> zlevel;
bool cmp(Node a, Node b){
	if(a.h != b.h)
		return a.h < b.h;
	else if(a.h % 2 == 0){ //当高度一致时,偶数层从右往左 (索引从大到小输出) 
		return a.index > b.index;
	}else{                 //奇数层,从左往右,(索引从 小 到 大 输出) 
		return a.index < b.index;
	}
}
void preOrder(int postright, int inleft, int inright,int index, int h){
	if(inleft > inright) return;
	int i = inleft;
	while(post[postright] != in[i]) i++;
//	Node node = Node();//注意此步是 Node 没有new  
//	node.data = post[postright];
//	node.h = h;
//	node.index = index;
	zlevel.push_back({h, index, post[postright]});
	preOrder(postright - (inright - i) -1, inleft, i - 1, index * 2 + 1, h + 1);
	preOrder(postright - 1, i + 1, inright, index * 2 + 2, h + 1);
}
int main(){
	scanf("%d", &n);
	in.resize(n); 
	post.resize(n);
	for(int i = 0; i < n; i++){
		scanf("%d", &in[i]); 
	}
	for(int i = 0; i < n; i++){
		scanf("%d", &post[i]);
	}
	preOrder(n - 1, 0, n - 1, 0, 0);
	sort(zlevel.begin(), zlevel.end(), cmp);
	for(int i = 0; i < n; i++){
		if(i != 0) 
			printf(" ");
		printf("%d", zlevel[i].data);
	}
	return 0;
} 

 

方法二:

           根据中序后序推出前序遍历通过链表建立树通过BFS 得到层次遍历,将结点按高度存放在result二维数组中

偶数高度 逆序输出 (从右向左)

奇数高度 正序输出(从左至右)

具体代码:

/**
思路 : 建立一颗树 将每层的结点通过BFS层序遍历分别放入二维向量数组 result[i]中(存放了在高度为i的全部结点) 
	   当高度为偶数时输出 倒序输出 
	   当高度为奇数时输出 正序输出   
**/
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
struct Node{
	Node *l, *r;
	int data, h;
};
int n, cnt = 0; //cnt用来保证最后输出的格式 
vector<int> post, in, result[35]; // 

queue<Node *> q;
Node *preOrder(Node *root, int postright, int inleft, int inright, int h){
	if(inleft > inright){
		return nullptr;
	}
	int i = inleft;
	while(post[postright] != in[i]) i++;
	root = new Node();
	root -> data = post[postright];
	root -> h    = h;
	root -> l = preOrder(root -> l, postright -(inright - i) - 1, inleft, i - 1, h + 1);
	root -> r = preOrder(root -> r, postright - 1, i + 1, inright, h + 1);
	return root;
}

void levelOrder(Node *root){
	q.push(root);
	while(!q.empty()){
		Node *n = q.front();
		q.pop();
	 	result[n->h].push_back(n->data);
		if(n->l != nullptr) 
			q.push(n->l);
		if(n->r != nullptr)
			q.push(n->r);
		}
} 

int main(){
    //k % 2 == 0表示从左至右遍历 k % 2 == 1 表示从右至左遍历 
	Node *root = nullptr;
	scanf("%d", &n);
	in.resize(n);
	post.resize(n);
	for(int i = 0; i < n; i++){
		scanf("%d", &in[i]);
	}
	for(int i = 0; i < n; i++){
		scanf("%d", &post[i]);
	}
	root = preOrder(root, n - 1, 0, n - 1, 0);	 //构建出一棵树 
	levelOrder(root); //进行层序遍历并就结点放入二维向量数组中 
	printf("%d", result[0][0]);
	for(int i = 1; i < n; i++){
		if(i % 2 == 1)
			for(int j = 0; j < result[i].size(); j++)
	            printf(" %d", result[i][j]);			
		if(i % 2 == 0)
			for(int j = result[i].size() - 1; j >= 0; j--)
				printf(" %d", result[i][j]);
	}
	return 0;
}

当然也可以不用链表 静态用数组表示树:

#include<iostream>
#include<vector>
#include<queue>
using namespace std;
struct Node{
	int lindex, rindex, h, index;
}node[35];
int n;
queue<Node> q; 
vector<int> in, post, result[35];
int preOrder(int postright, int inleft, int inright, int h){
	if(inleft > inright) return -1;
	int i = inleft;
	while(post[postright] != in[i]) i++;
	node[postright].index = postright;
	node[postright].h = h;
	node[postright].lindex = preOrder(postright - (inright - i) - 1, inleft, i - 1, h + 1);
	node[postright].rindex = preOrder(postright - 1, i + 1, inright, h + 1);
	return postright;
}

void levelBFS(int postright){
	q.push(node[postright]);
	while(!q.empty()){
		Node n = q.front();
		result[n.h].push_back(post[n.index]);
		q.pop();
		if(n.lindex != -1){
			q.push(node[n.lindex]);
		}
		if(n.rindex != -1){
			q.push(node[n.rindex]);
		}
	}
	
}
int main(){
	int n;
	scanf("%d", &n);
	in.resize(n);
	post.resize(n);
	for(int i = 0; i < n; i++){
		scanf("%d", &in[i]);
	}
	for(int i = 0; i < n; i++){
		scanf("%d", &post[i]);
	}
	preOrder(n - 1, 0, n - 1, 0);
	levelBFS(n - 1);
	printf("%d", result[0][0]);
	for(int i = 1; i < n; i++){
		if(i % 2 == 1)
			for(int j = 0; j < result[i].size(); j++)
	            printf(" %d", result[i][j]);			
		if(i % 2 == 0)
			for(int j = result[i].size() - 1; j >= 0; j--)
				printf(" %d", result[i][j]);
	} 
	return 0;
}

 

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_41698081/article/details/91633108

智能推荐

【蓝桥杯】第九届决赛 - 海盗与金币(Java题解)_长生的梦呓的博客-程序员宅基地

题目结果填空(满分29分)标题:海盗与金币12名海盗在一个小岛上发现了大量的金币,后统计一共有将近5万枚。登上小岛是在夜里,天气又不好。由于各种原因,有的海盗偷拿了很多,有的拿了很少。后来为了“均贫富”,头目提出一个很奇怪的方案:每名海盗都把自己拿到的金币放在桌上。然后开始一个游戏。金币最多的海盗要拿出自己的金币来补偿其他人。补偿的额度为正好使被补偿人的金币数目翻番(即变为原来的2...

win 10 Neo4j安装及配置 neo4j-community-4.3.6-windows_windows10安装neo4j_Ting廷帅的博客-程序员宅基地

一、官网下载Neo4j首先在Neo4j官网下载Neo4j社区版如果电脑没有JDK,要先安装JDK,在弹出的页面点击OpenJDK 8 or Oracle Java 8点击jdk.java.net/17点击java SE 11,java版本过新会导致后面Neo4j无法打开点击Windows/x64 Java Development Kit (sha256)JDK下载完成后解压到合适的路径,以下是我的安装路径:D:\Software\Neo4j\jdk-11Neo4j下载完成后解压到合_windows10安装neo4j

C++test 9.2 无法安装 重装_无法安装c++ test_明子1的博客-程序员宅基地

在安过程中发的该安装报错 文件 C:\Users\maym\AppData\Local\Xtest\C++test\InstallLog大家 根据该报错文件 提示 “VS2010 extensions directory: C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\Extensions\”找到_无法安装c++ test

阿里巴巴Java开发手册认证考试题库_威威超酷的博客-程序员宅基地

注转载自:https://baijiahao.baidu.com/s?id=1688631517911751367&wfr=spider&for=pc此文作用于自己刷题使用,答案在每道题的题干后面的括号中,选中即可显示。题目1-101.【多选】如何处理单元测试产生的数据,下列哪些说法是正确的?(ABC)A .测试数据入库时加特殊前缀标识。B .测试数据使用独立的测试库。C .自动回滚单元测试产生的脏数据。D .无须区别,统一在业务代码中进行判断和识别。简单解析:P29【推

解决 Windows 10 中的网络连接问题_网络适配器驱动程序 windows 10_MentoGDUT的博客-程序员宅基地

如果在连接到某个网络时遇到问题并且无法连接到 Internet,可以在 Windows 10 中尝试执行以下操作。MentoGDUT作者提醒: 网络重置会删除所有适配器和NDIS设备, 并且重置之后均需要重启, 注销当前用户不能取代系统重启。另外,如果PPPoE拨号提示720错误,则可能是协议出错了(包括但不限于协议缺少、损坏或者安装顺序不正常),请检查ms_pppoe, ms_ndiswan, ms_wanarp协议以及ms_pppoeminiport, ms_ndiswanip设备是否工作正常, 协议可_网络适配器驱动程序 windows 10

随便推点

切换host的工具switchhost_千雅爸爸的博客-程序员宅基地

https://github.com/oldj/SwitchHosts/downloads下载链接: 1,290 downloadsSwitchHosts! _v0.2.2.1790.dmg — SwitchHosts! v0.2.2.1790, Mac/Portable36.3MB · Uploaded on 3 Dec 2012 13,084 downl

收藏表 数据库设计_收藏功能数据库设计_will的猜想的博客-程序员宅基地

产品收藏功能,应该如何设计数据表有产品表 产品ID,产品名称有用户表现用户可以收藏产品,应该怎么设计数据表1.是在用户表里增加收藏列,以类似(产品ID)这样的方法存储?2.还是增加收藏表,以每个用户的每个收藏都当作一条数据?单独建立收藏表,基本没有在用户表中增加收藏列这种类似做法的。其次,每个用户的一次收藏作为_收藏功能数据库设计

操作系统原理 实验四 处理机调度_现系统中有五个进程,进程1取3000,进程2取3000,进程3存1000,进程4取2000,进程5_bearcat303295的博客-程序员宅基地

实验四 处理机调度1、实验目的多道程序设计中,往往有若干个进程同时处于就绪状态。当就绪进程个数大于处理器数时,就必须依照某种策略来决定哪些进程优先占用处理器。本实验模拟在单处理器情况下的处理器调度,帮助学生加深理解处理机调度算法。2、实验预备内容(1)C语言源程序的调试和编译知识。(2)掌握优先数调度算法和时间片轮转法的原理。3、实验内容(1)设计一个按优先数调度算法实现处理器调度的程序。[提示]:①假定系统有五个进程,每一个进程用一个进程控制块PCB来代表,进程控制块的格式为:其中,_现系统中有五个进程,进程1取3000,进程2取3000,进程3存1000,进程4取2000,进程5

mathml_MathML简介–数学标记语言-程序员宅基地

MathML是一种可用于显示数学符号的标记语言 。 您可以直接从HTML5使用MathML标签。 当您希望在网页中显示更多简单的数学符号时,它非常有用,并且由于其简单性和与HTML的相似性 ,因此非常易于使用。 MathML有两种标记: 展示(用于布局)和内容(用于含义)。 由于浏览器仅支持演示文稿标记,因此这是可与HTML一起使用的唯一标记类型。 您也可以像在HTML上一样在其上使用CS..._mathml

ural1057 Amount of degrees_qioipe的博客-程序员宅基地

ural1057 Amount of degreesDescription求给定区间[X,Y]中满足下列条件的整数个数:这个数恰好等于K个互不相等的B的整数次幂之和。例如,设X=15,Y=20,K=2,B=2,则有且仅有下列三个数满足题意:17 = 24+20,18 = 24+21,20 = 24+22。数据规模:1≤X≤Y≤2^31-1,1≤K≤20, 2≤B≤10Sample ...

推荐文章

热门文章

相关标签