1. 程式人生 > >PAT 1020 Tree Traversals

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; }