标签:中序遍历 strong ble other idt des col 后序 init
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 16273 Accepted Submission(s): 6823
给出二叉树的先序遍历与中序遍历,求后序遍历
因为对于先序遍历来说,最先输出的是根节点,而对于中序遍历来说,根节点的左边都是左子树,根据这一特点,可以写出递归调用
#include<bits/stdc++.h> using namespace std; int a[1005],b[1005]; struct node { int val; node *l,*r; }; node *root; node * pre_and_in_to_post(int *a,int *b,int n) //a控制当前子树的先序遍历,b为中序,n为当前子树的长度 { node *now; for(int i=0;i<n;i++) { if(a[0]==b[i]) //找到当前的根节点 { now=(node *)malloc(sizeof(node)); now->val=b[i]; now->l=pre_and_in_to_post(a+1,b,i); //中序遍历的根节点左边的都在左子树上 now->r=pre_and_in_to_post(a+i+1,b+i+1,n-i-1); return now; } } return NULL; } void postorder(node *t) { if(t!=NULL) { postorder(t->l); postorder(t->r); if(t==root) cout<<t->val<<endl; else cout<<t->val<<‘ ‘; } } int main() { int n; while(cin>>n) { root=NULL; for(int i=0;i<n;i++) { cin>>a[i]; } for(int i=0;i<n;i++) { cin>>b[i]; } root=pre_and_in_to_post(a,b,n); node *h=root; postorder(h); } }
HDU 1710 Binary Tree Traversals(二叉树)
标签:中序遍历 strong ble other idt des col 后序 init
原文地址:https://www.cnblogs.com/dyhaohaoxuexi/p/12771676.html