知道先序和中序,求后序以及层次遍历



  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <string.h>  
  4. char a[100000],b[100000];  
  5. struct node  
  6. {  
  7.     char data;  
  8.     struct node *l,*r;  
  9. };  
  10. struct node *creat(char *a,char *b,int n)//重建树  
  11. {  
  12.     if(n<=0)  
  13.         return NULL;  
  14.     struct node *root;  
  15.     root=(struct node *)malloc(sizeof(struct node));  
  16.     root->data=*a;  
  17.     int i;  
  18.     for(i=0; i<n; i++)  
  19.     {  
  20.         if(b[i]==*a)  
  21.             break;  
  22.     }  
  23.     root->l=creat(a+1,b,i);//左右分开建树  
  24.     root->r=creat(a+i+1,b+i+1,n-i-1);  
  25.     return root;  
  26. }  
  27. void last(struct node *root)//后序遍历  
  28. {  
  29.     if(root!=NULL)  
  30.     {  
  31.         last(root->l);  
  32.         last(root->r);  
  33.         printf("%c",root->data);  
  34.     }  
  35. }  
  36. void ceng(struct node *root)//层次遍历  
  37. {  
  38.     struct node *z[100000],*p;//用栈进行左右层次遍历  
  39.     int jin,chu;  
  40.     jin=chu=0;  
  41.     z[jin++]=root;  
  42.     while(chu<jin)  
  43.     {  
  44.         p=z[chu++];  
  45.         printf("%c",p->data);  
  46.         if(p->l!=NULL)  
  47.             z[jin++]=p->l;  
  48.         if(p->r!=NULL)  
  49.             z[jin++]=p->r;  
  50.     }  
  51. }  
  52. int main()  
  53. {  
  54.     int t,len;  
  55.     scanf("%d",&t);  
  56.     struct node *root;  
  57.     while(t--)  
  58.     {  
  59.         scanf("%s",a);  
  60.         scanf("%s",b);  
  61.         len=strlen(a);  
  62.         root=creat(a,b,len);  
  63.         last(root);  
  64.         printf("\n");  
  65.         ceng(root);  
  66.         printf("\n");  
  67.     }  
  68.     return 0;  
  69. }  
  70.    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值