二叉树模板

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <malloc.h>
  4 typedef int  ElemType; //数据类型
  5 
  6 //定义二叉树结构,与单链表相似,多了一个右孩子结点
  7 typedef struct BiTNode
  8 {
  9     ElemType  data; //数据域
 10     struct BiTNode
 11         *lChild, *rChlid; //左右子树域
 12 } BiTNode, *BiTree;
 13 
 14 //先序创建二叉树
 15 int CreateBiTree(BiTree *T)
 16 {
 17     ElemType ch;
 18     ElemType temp;
 19     scanf("%d", &ch);
 20     temp = getchar();
 21     if (ch == -1)
 22         *T = NULL;
 23     else
 24     {
 25         *T = (BiTree)malloc(sizeof(BiTNode));
 26         if (!(*T))
 27             exit(-1);
 28         (*T)->data = ch;
 29         printf("输入%d的左子节点:", ch);
 30         CreateBiTree(&(*T)->lChild);
 31         printf("输入%d的右子节点:", ch);
 32         CreateBiTree(&(*T)->rChlid);
 33     }
 34     return 1;
 35 }
 36 
 37 //先序遍历二叉树
 38 void TraverseBiTree(BiTree T)
 39 {
 40     if (T == NULL)
 41         return ;
 42     printf("%d ", T->data);
 43     TraverseBiTree(T->lChild);
 44     TraverseBiTree(T->rChlid);
 45 
 46 
 47 }
 48 
 49 //中序遍历二叉树
 50 void InOrderBiTree(BiTree T)
 51 {
 52     if (T == NULL)
 53         return ;
 54     InOrderBiTree(T->lChild);
 55     printf("%d ", T->data);
 56     InOrderBiTree(T->rChlid);
 57 
 58 
 59 }
 60 
 61 
 62 //后序遍历二叉树
 63 void PostOrderBiTree(BiTree T)
 64 {
 65     if (T == NULL)
 66         return ;
 67     PostOrderBiTree(T->lChild);
 68     PostOrderBiTree(T->rChlid);
 69     printf("%d ", T->data);
 70 }
 71 
 72 //二叉树的深度
 73 
 74 int TreeDeep(BiTree T)
 75 {
 76     int deep = 0;
 77     if(T)
 78     {
 79         int leftdeep = TreeDeep(T->lChild);
 80         int rightdeep = TreeDeep(T->rChlid);
 81         deep = leftdeep>=rightdeep?leftdeep+1:rightdeep+1;
 82     }
 83     return deep;
 84 }
 85 
 86 //求二叉树叶子结点个数
 87 
 88 int Leafcount(BiTree T,int &num)
 89 {
 90     if(T)
 91     {
 92         if(T->lChild ==NULL &&T->rChlid==NULL)
 93 
 94             num++;
 95         Leafcount(T->lChild,num);
 96         Leafcount(T->rChlid,num);
 97 
 98 
 99     }
100     return num;
101 }
102 //主函数
103 int main(void)
104 {
105     BiTree T;
106     BiTree *p = (BiTree*)malloc(sizeof(BiTree));
107     int deepth,num=0 ;
108     printf("请输入第一个结点的值,-1表示没有叶结点:\n");
109     CreateBiTree(&T);
110     printf("先序遍历二叉树:\n");
111     TraverseBiTree(T);
112     printf("\n");
113     printf("中序遍历二叉树:\n");
114     InOrderBiTree(T);
115     printf("\n");
116     printf("后序遍历二叉树:\n");
117     PostOrderBiTree(T);
118     printf("\n");
119     deepth=TreeDeep(T);
120     printf("树的深度为:%d",deepth);
121     printf("\n");
122     Leafcount(T,num);
123     printf("树的叶子结点个数为:%d",num);
124     printf("\n");
125     return 0;
126 }

 

posted @ 2018-06-10 13:26  王陸  阅读(583)  评论(0编辑  收藏  举报