A1127 ZigZagging on a Tree (30分)

一、技术总结

  1. 这一题是已知中序和后序遍历的结果,然后确定二叉树,然后将这棵树使用层序遍历输出,但是这个层序遍历输出有要求,首先将根结点输出,然后下一层从左到右遍历,再下一层从右到左遍历输出。
  2. 首先创建结点,元素应该包括层数;然后编写create函数,该函数的结束条件是,不管是先序还是后序,都是左边结点下标大于右边结点下标。然后创造根结点,就以当前题为例,后序遍历的最右边肯定为根结点,即赋值,之后就是使用后序中最右边结点的值,去中序遍历中寻找,找到后即为根结点,那么我们就可以知道左子树中结点的数量,以及右子树中结点的数量,然后分别对该结点的左子树和右子树,递归创建。numLeft = k - inL;左子树中序,后序传参下标为:inL, K-1, postL, postL+numLeft-1;右子树中序,后序传参下标为:k+1, inR, postL+numLeft, postR-1
  3. 然后是使用深度搜索,进行层序遍历,将每一层的结点保存到result中。
  4. 最后将结果进行按要求输出。

二、参考代码

#include<iostream> 
#include<bits/stdc++.h>
using namespace std;
struct node{
	int v, h;
	node* L;
	node* R;
};
vector<int> result[35];
vector<int> in, post;
node* create(int inL, int inR, int postL, int postR){
	if(postL > postR){
		return NULL;
	}
	node* root = new node;
	root->v = post[postR];
	int k;
	for(k = inL; k <= inR; k++){
		if(in[k] == post[postR]){
			break;
		}
	}
	int numLeft = k - inL;
	root->L = create(inL, k - 1, postL, postL + numLeft - 1);
	root->R = create(k + 1, inR, postL+numLeft, postR - 1);
	return root;
}
void bfs(node* root){
	queue<node*> q;
	root->h = 0;
	q.push(root);
	while(!q.empty()){
		node* now = q.front();
		q.pop();
		result[now->h].push_back(now->v);
		if(now->L != NULL){
			now->L->h = now->h + 1;
			q.push(now->L); 
		}
		if(now->R != NULL){
			now->R->h = now->h + 1;
			q.push(now->R);
		}
	}	
}
int main(){
	int n;
	scanf("%d", &n);
	for(int i = 0; i < n; i++){
		int a;
		scanf("%d", &a);
		in.push_back(a);
	}
	for(int i = 0; i < n; i++){
		int a;
		scanf("%d", &a);
		post.push_back(a);
	}
	node* root = create(0, n-1, 0, n-1);
	bfs(root);
	printf("%d", result[0][0]);
	for(int i = 1; i < 35; i++){
		if(i % 2 == 1){
			for(int j = 0; j < result[i].size(); j++){
				printf(" %d", result[i][j]);
			}
		}else{
			for(int j = result[i].size() - 1; j >= 0; j--){
				printf(" %d", result[i][j]);
			}
		}
	}
	return 0;
}
posted @ 2020-06-08 21:30  睿晞  阅读(175)  评论(0编辑  收藏  举报