码迷,mamicode.com
首页 > 其他好文 > 详细

1020. Tree Traversals (25)

时间:2017-10-09 13:11:11      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:遍历   queue   seq   bin   name   nta   nod   ace   enc   

Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.

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 postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the level order traversal sequence of the corresponding binary tree. 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:

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

Sample Output:

4 1 6 3 5 7 2


题目大意:由二叉树的中序遍历和后序遍历求出层序遍历的结果。

#include<iostream>
#include<stdio.h>
#include<cstring>
#include<queue>
#include<stdlib.h>
using namespace std;
int N;
#define  max 40
int postorder[max];
int inorder[max];
int cnt;
struct tree{
	struct tree *left;
	struct tree *right;
	int num;
};
int searchValue(int num){
	int i;
	for(i=0;i<N;i++){
		if(inorder[i]==num){
			return i;
		}
	}
	return -1;
}
tree * createTree(int left, int right){
	if(left > right)return NULL;
	int root = postorder[cnt];
	cnt --;
	int rootChild = searchValue(root);
	tree* t= (tree*)malloc(sizeof(tree));
	t->num = root;
	if(left == right){
		t->left = NULL;
		t->right = NULL;
	} 
	else{
		t->right = createTree(rootChild+1,right);
		t->left = createTree(left,rootChild-1);
		//cout<<"hello world"<<endl;
	}
	return t;
} 
void output(tree * t){
	int levelorder[max];
	queue<tree*>q_tree;
	q_tree.push(t);
	int i=0;
	levelorder[i++]=t->num;
	while(!q_tree.empty()){
		tree* index = q_tree.front();
		q_tree.pop();
		if(index->left!=NULL){
			q_tree.push(index->left);
			levelorder[i++]=index->left->num;
		}
		if(index->right!=NULL){
			q_tree.push(index->right);
			levelorder[i++]=index->right->num;
		}
	}
	int j;
	for(j=0;j<i;j++){
		if(j+1==i){
			printf("%d\n",levelorder[j]);
		}
		else{
			printf("%d ",levelorder[j]);
		}
	}
}
int main(){
	scanf("%d",&N);
	int i,j;
	for(i=0;i<N;i++){
		scanf("%d",&postorder[i]);
	}
	for(j=0;j<N;j++){
		scanf("%d",&inorder[j]);
	}
	cnt = N-1;
	tree* tt=createTree(0,N-1);
	//cout<<"hello world"<<endl;
	output(tt);
	return 0;
}

  

1020. Tree Traversals (25)

标签:遍历   queue   seq   bin   name   nta   nod   ace   enc   

原文地址:http://www.cnblogs.com/grglym/p/7640533.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!