HDU

来源:互联网 发布:qq农场运输机数据 编辑:程序博客网 时间:2024/06/03 19:09

A 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. 
Input
The 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. 
Output
For 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


题意:给你前序,中序遍历,让你输出后序遍历;

题解:和构建二叉树差不多,代码里,有解释;

代码:

#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;#define Max 1010int f;void build(int n,int *s1,int *s2){if(n<=0) return ;   int i,p;for(i=0;i<n;i++)  // 找出以s1[0]为根节点的左子树; {if(s2[i]==s1[0])break; }p = i;build(p,s1+1,s2);           //构建左子树;p是以s1[0] 为根节点的左子树的结点个数;build(n-p-1,s1+p+1,s2+p+1); //构建右子树,n-p-1就是以s1[0]为根节点的右子树的结点个数;   //s2[0] 永远就是以s1[0]为根节点的树的中序遍历的第一个节点; if(!f){printf("%d",s1[0]);f=1;}else printf(" %d",s1[0]);}int main(){int i,j,n;int s1[Max],s2[Max];while(~scanf("%d",&n)){for(i=0;i<n;i++)scanf("%d",&s1[i]);for(i=0;i<n;i++)scanf("%d",&s2[i]);f=0;build(n,s1,s2);printf("\n");}return 0;}






原创粉丝点击