PAT (Advanced Level) Practice 1020 Tree Traversals (25 分)
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 <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <vector> #include <malloc.h> #include <queue> using namespace std; int n; vector<int>pre,in,post; int loc; struct node { int data; node * left,*right; }; int finds (int x) { for (int i=0;i<n;i++) { if(in[i]==x) return i; } return -1; } node* create (int l,int r) { if(l>r) { return NULL; } int root=post[loc--]; int m=finds(root); node* t=(node*)malloc(sizeof(node)); t->data=root; if(l==r) { t->left=t->right=NULL; } else { t->right=create(m+1,r); t->left=create(l,m-1); } return t; } void Traverse (node* t) { queue<node*>q; if(t) q.push(t); int flag=0; while(!q.empty()) { node* tt=q.front(); q.pop(); if(!flag) { flag=1; printf("%d",tt->data); } else { printf(" %d",tt->data); } if(tt->left) { q.push(tt->left); } if(tt->right) { q.push(tt->right); } } printf("\n"); } int main() { scanf("%d",&n); loc=n-1; for (int i=0;i<n;i++) { int x; scanf("%d",&x); post.push_back(x); } for (int i=0;i<n;i++) { int x; scanf("%d",&x); in.push_back(x); } node* root=create(0,n-1); Traverse(root); return 0; }