두 갈래 트리 반복 작업 M

14091 단어 두 갈래 나무
  1 #include<stdio.h>

  2 #include<stdlib.h>

  3 #define ok 1

  4 #define error 0

  5 typedef int status;

  6 typedef char  TElemType;

  7 typedef struct BiTNode

  8 {

  9    TElemType data;

 10    struct BiTNode *lchild,*rchild;

 11 }BiTNode,*BiTree;

 12 

 13 void InitBiTree(BiTree &T)

 14 {

 15    T=NULL;

 16 }

 17 void DestroyBiTree(BiTree &T)

 18 {

 19    if(T)

 20    {

 21      DestroyBiTree(T->lchild);

 22      DestroyBiTree(T->rchild);

 23      free(T);

 24      T=NULL;

 25    }

 26 }

 27 status CreateBiTree(BiTree &T)

 28 {

 29    char ch;

 30    ch=getchar();

 31    if(ch==' ')  T=NULL;

 32    else

 33    {

 34        if(!(T=(BiTNode *)malloc(sizeof(BiTNode))))  exit(error);

 35        T->data=ch;

 36        CreateBiTree(T->lchild);

 37        CreateBiTree(T->rchild);

 38    }

 39    return ok;

 40 }

 41 void PreOrderTraverse(BiTree T)

 42 {

 43    if(T)

 44    {

 45        printf("%c",T->data);

 46        PreOrderTraverse(T->lchild);

 47        PreOrderTraverse(T->rchild);

 48    }

 49 }

 50 void InOrderTraverse(BiTree T)

 51 {

 52    if(T)

 53    {

 54        InOrderTraverse(T->lchild);

 55        printf("%c",T->data);

 56        InOrderTraverse(T->rchild);

 57    }

 58 }

 59 void PostOrderTraverse(BiTree T)

 60 {

 61    if(T)

 62    {

 63        PostOrderTraverse(T->lchild);

 64        PostOrderTraverse(T->rchild); 

 65        printf("%c",T->data);

 66    }

 67 }

 68 status CountLeaf(BiTree T)

 69 {

 70    int count=0;

 71    if(T)

 72    {

 73       if((!T->lchild)&&(!T->rchild))

 74       count++;    

 75       count+=CountLeaf( T->lchild);  

 76       count+=CountLeaf( T->rchild); 

 77    }

 78    return count;

 79 }

 80 status Depth(BiTree T)

 81 { 

 82    int depthval=0;

 83    int depthLeft,depthRight;

 84    if(!T)    depthval = 0;

 85    else   

 86    {

 87      depthLeft = Depth( T->lchild );

 88      depthRight= Depth( T->rchild );

 89      depthval = 1 + (depthLeft > depthRight ? depthLeft : depthRight);

 90    }    

 91    return depthval;

 92 } 

 93 int main()

 94 {

 95     BiTree T;

 96     InitBiTree(T);

 97     int count,depthval;

 98     printf(" 
"); 99 CreateBiTree(T); 100 printf("
"); 101 PreOrderTraverse(T); 102 putchar('
'); 103 printf("
"); 104 InOrderTraverse(T); 105 putchar('
'); 106 printf("
"); 107 PostOrderTraverse(T); 108 putchar('
'); 109 count=CountLeaf(T); 110 printf(" :%d
",count); 111 depthval=Depth(T); 112 printf(" :%d
",depthval); 113 system("pause"); 114 return 0; 115 }

좋은 웹페이지 즐겨찾기