1020 Tree Traversals (25 分)
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 <iostream> #include <algorithm> #include <cstdio> #include <cstring> #include <stack> #include <queue> using namespace std; const int maxn = 1005; int in_order[maxn],post_order[maxn]; int n,flag; int lch[maxn],rch[maxn]; queue<int> que; int build_tree(int l1,int r1,int l2,int r2) { if(l1 > r1) return 0; int root = post_order[r2]; //當前區間中的根節點 int pos = l1; while(in_order[pos] != root) pos++; //在中序遍歷中找到根節點的位置,將序列分成左右兩個區間 int cnt = pos - l1; //左子樹區間的長度 lch[root] = build_tree(l1,pos-1,l2,l2+cnt-1); //遍歷左子樹 rch[root] = build_tree(pos+1,r1,l2+cnt,r2-1); //遍歷右子樹 return root; } void BFS(int root) { que.push(root); while(!que.empty()) { int node = que.front(); que.pop(); if(!flag) printf("%d",node),flag = 1; else printf(" %d",node); if(lch[node]) que.push(lch[node]); if(rch[node]) que.push(rch[node]); } } int main() { scanf("%d",&n); for(int i = 0;i < n;i ++) scanf("%d",post_order+i); for(int i = 0;i < n;i ++) scanf("%d",in_order+i); int root = build_tree(0,n-1,0,n-1); BFS(root); printf("\n"); }