PAT 1020 Tree Traversals

1020 Tree Traversals

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<cstdio>
#include<queue>
using namespace std;
int a[50],b[50];//后序中序 
queue<int> Q;
struct Tree{
	int left;
	int right;
}tree[100];
int root=-1;
int dfs(int l1,int r1,int l2,int r2){
	if(l1<=r1&&l2<=r2){
		int root=a[r1],ind=-1;
		for(int i=l2;i<=r2;i++){
			if(b[i]==root){
				ind=i;
				break;
			}
		}	
		tree[root].left=dfs(l1,l1+(ind-1-l2),l2,ind-1);//根据ind分成左右子树两部分
		tree[root].right=dfs(r1-1-(r2-ind-1),r1-1,ind+1,r2);
//		printf("%d\n",root);
		return root;//
	}
	return 0;
}
void print(int root){
	if(root!=0) printf("%d",root);
	Q.push(root);
	while(!Q.empty()){
		int root=Q.front();
		Q.pop();
		if(tree[root].left!=0){
			printf(" %d",tree[root].left);
			Q.push(tree[root].left);
		}
		if(tree[root].right!=0){
			printf(" %d",tree[root].right);
			Q.push(tree[root].right);
		}
	}
}
int main(int argc, char** argv) {
	int n;
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
		scanf("%d",&a[i]);
	}
	for(int i=1;i<=n;i++){
		scanf("%d",&b[i]);
	}
	int root=dfs(1,n,1,n);
	print(root);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/zhuixun_/article/details/83097239