Binary Tree Traversals
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2468 Accepted Submission(s): 1072
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.
inorder sequence. You can assume they are always correspond to a exclusive binary tree.
9 1 2 4 7 3 5 8 9 6 4 7 2 1 8 5 9 3 6
7 4 2 8 9 5 6 3 1
Code:
由前序遍历和终须遍历求后序遍历, 递归, 分清序列
#include"stdio.h" #include"string.h" int s1=1,s3=1;//前序和后序的序号 int preseq[1010],inseq[1010],postseq[1010]; void find(int a,int b)//表示是从a~b的一棵树 { int i; if(a>b) return;//该树没有元素 if(a==b)//只有一个元素 { //直接将该元素存入postseq,s1++,判断preseq的下一个元素 postseq[s3++] = inseq[a]; s1++; return; } // printf("** "); preseq[0] = preseq[s1]; //寻找根在inpost中的位置 for(i=a;inseq[i]!=preseq[0];i++); s1++; find(a,i-1);//左子树 find(i+1,b);//右子树 postseq[s3++] = inseq[i];//根 } int main() { int i,n; while(scanf("%d",&n)!=EOF) { for(i=1;i<=n;i++) scanf("%d",&preseq[i]); for(i=1;i<=n;i++) scanf("%d",&inseq[i]); find(1,n); for(i=1;i<n;i++)//输出 printf("%d ",postseq[i]); printf("%d\n",postseq[n]); s1 = 1;s3 = 1;//序号重新变回1 } return 0; } /* 9 1 2 4 7 3 5 8 9 6 4 7 2 1 8 5 9 3 6 */