二叉树输出

在学习二叉树遍历的时候我们学习了三种遍历方法 前序 中序 后序 

同时我们知道给定前序和中序、中序和后序我们可以还原二叉树, 

记得当时只是在纸上画了一画。现在把当时的想法完成。

给定前序和中序生成二叉树。。。

[cpp]  view plain  copy
  1. #include <iostream>  
  2. /** 
  3.     在学习二叉树遍历的时候我们学习了三种遍历方法 前序 中序 后序 
  4.     同时我们知道给定前序和中序、中序和后序我们可以还原二叉树, 
  5.     记得当时只是在纸上画了一画。现在把当时的想法完成。 
  6.  
  7.     给定前序和中序还原二叉树。。。 
  8. */  
  9.   
  10. using namespace std;  
  11.   
  12. typedef struct node  
  13. {  
  14.    char value;  
  15.    struct node *lh;  
  16.    struct node *rh;  
  17. }node;  
  18.   
  19. node* buildtree(char pre[],char mid[],int n) //n为子树结点个数  
  20. {  
  21.      if(n == 0) return 0;  
  22.      node *p = new node;  
  23.      p->value = pre[0];  
  24.      int i;  
  25.      for(i=0;i<n;i++)  
  26.      {  
  27.          if(mid[i] == pre[0]) break;  
  28.      }  
  29.      p->lh = buildtree(pre+1,mid,i);  
  30.      p->rh = buildtree(pre+i+1 ,mid+i+1,n-i-1);  
  31.      return p;  
  32. }  
  33.   
  34. void print(node *root)  
  35. {  
  36.        if(root == 0) return;  
  37.         cout<<root->value<<" ";  
  38.         print(root->lh);  
  39.         print(root->rh);  
  40. }  
  41.   
  42. int main()  
  43. {  
  44.    char pre[10];  
  45.    char mid[10];  
  46.    int n;//树结点数  
  47.    cin>>n;  
  48.    cin>>pre;  
  49.    cin>>mid;  
  50.    node *p;  
  51.     p = buildtree(pre,mid,n);  
  52.     print(p);  
  53.     return 0;  

  1. }  


preorder(bitree t)

{

    if(t==null)return;

    print---t->data

    preorder(t-left)

    preorder(t-right

}



猜你喜欢

转载自blog.csdn.net/a133900029/article/details/80601830