标签:数组 scanf clu ring turn roo max for 中序
PTA
03-树3 Tree Traversals Again
1 #include<stdio.h> 2 #include<string.h> 3 #define MAXSIZE 30 4 5 int Pre[MAXSIZE],In[MAXSIZE],Post[MAXSIZE]; 6 void solve(int preL,int inL,int postL,int n); 7 void outPut(int p[],int n); 8 9 int main(){ 10 int n,tmp,i,j = 0; 11 int topPre = -1; 12 int topIn = -1; 13 const char *push = "Push"; 14 char cnt[5]; 15 int st[MAXSIZE]; 16 scanf("%d",&n); 17 for(i=0; i<2*n; i++){ 18 scanf("\n%s",cnt); 19 if(!strcmp(cnt,push)){ 20 scanf("%d",&tmp); 21 Pre[j++] = tmp; 22 st[++topPre] = tmp; 23 }else{ 24 In[++topIn] = st[topPre--]; 25 } 26 } 27 solve(0,0,0,n); 28 outPut(Post,n); 29 return 0; 30 } 31 32 void solve(int preL, int intL, int postL, int n){ 33 int i,L,R,root; 34 if(n==0) return; 35 if(n==1) {Post[postL] = Pre[preL]; return;} 36 root = Pre[preL]; 37 Post[postL+n-1] = root; 38 for(i=0; i<n; i++) if(In[intL+i]==root) break; 39 L = i;R = n-L-1; 40 solve(preL+1, intL, postL, L); 41 solve(preL+L+1, intL+L+1, postL+L, R); 42 } 43 44 void outPut(int p[],int n){ 45 int i; 46 for(i=0; i<n; i++){ 47 if(!i) printf("%d",p[i]); 48 else printf(" %d",p[i]); 49 } 50 }
分析:
1、定义全局数组,Pre是对应先序遍历的输入,In是对应中序遍历的出栈,Post是对应后序遍历的输出
2、处理输入的过程用了栈的思路
3、solve()用了分治
标签:数组 scanf clu ring turn roo max for 中序
原文地址:https://www.cnblogs.com/cxc1357/p/10800320.html