標籤:des style blog http color java os io
Binary Tree Traversals
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3340 Accepted Submission(s): 1500
Problem DescriptionA binary tree is a finite set of vertices that is either empty or consists of a root r and two disjoint binary trees called the left and right subtrees. There are three most important ways in which the vertices of a binary tree can be systematically traversed or ordered. They are preorder, inorder and postorder. Let T be a binary tree with root r and subtrees T1,T2.
In a preorder traversal of the vertices of T, we visit the root r followed by visiting the vertices of T1 in preorder, then the vertices of T2 in preorder.
In an inorder traversal of the vertices of T, we visit the vertices of T1 in inorder, then the root r, followed by the vertices of T2 in inorder.
In a postorder traversal of the vertices of T, we visit the vertices of T1 in postorder, then the vertices of T2 in postorder and finally we visit r.
Now you are given the preorder sequence and inorder sequence of a certain binary tree. Try to find out its postorder sequence.
InputThe input contains several test cases. The first line of each test case contains a single integer n (1<=n<=1000), the number of vertices of the binary tree. Followed by two lines, respectively indicating the preorder sequence and inorder sequence. You can assume they are always correspond to a exclusive binary tree.
OutputFor each test case print a single line specifying the corresponding postorder sequence.
Sample Input
91 2 4 7 3 5 8 9 64 7 2 1 8 5 9 3 6
Sample Output
7 4 2 8 9 5 6 3 1今天刷二叉樹專題,搞了半天終於對重建有了一點認識,首先說一下由先序和中序重建二叉樹,大體思路是大概是這樣的:因為先序(pre)的第一個字母肯定是根節點,所以要在中序(ins)序列中找到根節點的位置k,然後遞迴重建根節點的左子樹和右子樹。此時要把左子樹和右子樹當成根節點,然後表示出它們的位置,左子樹很好說,pre+1就是它的位置,對於右子樹來說,pre+k+1為它的位置,對於由中序和後序重建,思路跟上面大體一樣,具體寫法有點差別,這個就要在中序序列中找到後序的最後一個字母(即根節點),然後遞迴重建左子樹和右子樹,依舊是把左子樹和右子樹當成根節點,左子樹的位置為pos+k-1,但傳的參數應該是pos (因為我們要找的字母是pos[n-1]),而右子樹的位置在後序的倒數第二個字母,傳參數為pos+k,(不是pos+k+1,想明白這個就算真明白了)另為這篇沒寫由後序和中序重建的代碼,以前寫過,在這點擊開啟連結#include <cstdio>#include <iostream>#include <algorithm>#include <cstring>#include <cctype>#include <cmath>#include <cstdlib>#include <vector>#include <queue>#include <set>#include <map>#include <list>using namespace std;const int INF=1<<27;const int maxn=5100;typedef struct node{int data;node *l,*r;}*T;void rbuild(T &root,int *pre,int *ins,int n){ if(n<=0)root=NULL; else { root=new node; int k=find(ins,ins+n,pre[0])-ins;root->data=pre[0];rbuild(root->l,pre+1,ins,k);rbuild(root->r,pre+k+1,ins+k+1,n-k-1); }}int ans[maxn],p;void last(T root){if(root){last(root->l);last(root->r);ans[p++]=root->data;}}int main(){int n,i;while(cin>>n){T root;int pre[maxn],ins[maxn];for(i=0;i<n;i++)cin>>pre[i];for(i=0;i<n;i++)cin>>ins[i];rbuild(root,pre,ins,n);p=0;last(root);for(i=0;i<p;i++)if(i!=p-1)cout<<ans[i]<<" "; elsecout<<ans[i]<<endl;}return 0;}