SDUTOJ 2173 数据结构实验之求二叉树后序遍历和层次遍历

来源:互联网 发布:ubuntu caffe 编辑:程序博客网 时间:2024/05/29 04:15
[cpp] view plain copy
  1. #include<iostream>  
  2. #include<stdio.h>  
  3. #include<queue>  
  4. #include<string.h>  
  5. #include<stdlib.h>  
  6. using namespace std;  
  7. char s1[100],s2[100],ans[100];  
  8. typedef struct BiTNode  
  9. {  
  10.     char data;  
  11.     struct BiTNode *lchild,*rchild;  
  12. }BiTNode,*BiTree;  
  13. void build(BiTree &T,char *s1,char *s2,int n)//利用前序遍历和中序遍历恢复二叉树  
  14. {  
  15.     if(n<=0) T=NULL;  
  16.     else  
  17.     {  
  18.         int p=strchr(s2,s1[0])-s2;  
  19.         T=new BiTNode;  
  20.         T->data=s1[0];  
  21.         build(T->lchild,s1+1,s2,p);//递归创建左子树  
  22.         build(T->rchild,s1+p+1,s2+p+1,n-p-1);//递归创建右子树  
  23.     }  
  24. }  
  25. void build1(int n,char *s1,char *s2,char *s)//根据前序遍历和中序遍历求后序遍历  
  26. {  
  27.      if(n<=0) return ;  
  28.      else  
  29.      {  
  30.          int p=strchr(s2,s1[0])-s2;  
  31.          build1(p,s1+1,s2,s);  
  32.          build1(n-p-1,s1+p+1,s2+p+1,s+p);  
  33.          s[n-1]=s1[0];  
  34.      }  
  35. }  
  36. void levelOrder(BiTree T)//bfs算法完成层次遍历,使用队列存储数据。  
  37. {  
  38.     BiTree p=T;  
  39.     queue<BiTree>queue;  
  40.     queue.push(p);  
  41.     while(!queue.empty())  
  42.     {  
  43.         p=queue.front();  
  44.         cout<<p->data;  
  45.         queue.pop();  
  46.         if(p->lchild!=NULL)  
  47.         {  
  48.             queue.push(p->lchild);  
  49.         }  
  50.         if(p->rchild!=NULL)  
  51.         {  
  52.             queue.push(p->rchild);  
  53.         }  
  54.     }  
  55. }  
  56. int main()  
  57. {  
  58.     BiTree T;  
  59.     int n,len;  
  60.     cin>>n;  
  61.     while(n--)  
  62.     {  
  63.         cin>>s1>>s2;  
  64.         len=strlen(s1);  
  65.         build(T,s1,s2,len);  
  66.         build1(len,s1,s2,ans);  
  67.         ans[len]='\0';  
  68.         cout<<ans<<endl;  
  69.         levelOrder(T);  
  70.         cout<<endl;  
  71.     }  
  72.     return 0;  

  73. 转载地址http://blog.csdn.net/r_misaya/article/details/40396607
0 0
原创粉丝点击