标签:des style blog http color io os java ar
http://acm.hdu.edu.cn/showproblem.php?pid=1710
已知先序和中序遍历,求后序遍历二叉树。
思路:先递归建树的过程,后后序遍历。
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3442 Accepted Submission(s): 1541
#include<iostream> #include<cstring> #include<cstdio> #include<stdlib.h> using namespace std; int m; typedef struct tree { tree *l,*r; int num; }tree; tree *creat(int *a,int *b,int n) { tree *t; int i; for(i=0;i<n;i++) { if(a[0]==b[i])//找到中序遍历时的根节点 { t=(tree*)malloc(sizeof(tree)); t->num=b[i]; t->l=creat(a+1,b,i);//中序历遍中在根节点左边的都是左子树上的 t->r=creat(a+i+1,b+i+1,n-i-1);//在根节点右边的,都是右子树上的,右子树需要从i+1开始 return t; } } return NULL; } void postorder(tree *root)//后序遍历。 { if(root!=NULL) { postorder(root->l); postorder(root->r); if(m==root->num) printf("%d\n",root->num); else printf("%d ",root->num); } } int main() { int i,n; int a[2005],b[2005]; while(~scanf("%d",&n)) { tree *root; for(i=0;i<n;i++) scanf("%d",&a[i]); for(i=0;i<n;i++) scanf("%d",&b[i]); root=creat(a,b,n); m=a[0]; // printf("root=%d\n",root->num); postorder(root); } return 0; }
HDU-1701 Binary Tree Traversals
标签:des style blog http color io os java ar
原文地址:http://www.cnblogs.com/cancangood/p/3989265.html