1-4 二叉树求深度和叶子数
分数 3
作者 鲁法明
单位 浙江大学
编写函数计算二叉树的深度以及叶子节点数。二叉树采用二叉链表存储结构
函数接口定义:
1 2
| int GetDepthOfBiTree ( BiTree T); int LeafCount(BiTree T);
|
其中 T是用户传入的参数,表示二叉树根节点的地址。函数须返回二叉树的深度(也称为高度)。
裁判测试程序样例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| #include<stdlib.h> #include<stdio.h> #include<malloc.h>
#define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define OVERFLOW -1 #define INFEASIBLE -2 #define NULL 0 typedef int Status;
typedef int TElemType; typedef struct BiTNode{ TElemType data; struct BiTNode *lchild, *rchild; } BiTNode, *BiTree;
Status CreateBiTree(BiTree &T){ TElemType e; scanf("%d",&e); if(e==0)T=NULL; else{ T=(BiTree)malloc(sizeof(BiTNode)); if(!T)exit(OVERFLOW); T->data=e; CreateBiTree(T->lchild); CreateBiTree(T->rchild); } return OK; }
int GetDepthOfBiTree ( BiTree T); int LeafCount(BiTree T);
int main() { BiTree T; int depth, numberOfLeaves; CreateBiTree(T); depth= GetDepthOfBiTree(T); numberOfLeaves=LeafCount(T); printf("%d %d\n",depth,numberOfLeaves); }
|
输入样例:
输出样例:
答案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| int GetDepthOfBiTree ( BiTree T) { int m, n; if (T == NULL) { return 0; } else { m = GetDepthOfBiTree(T->lchild); n = GetDepthOfBiTree(T->rchild); if (m > n) { return m + 1; }else { return n + 1; } } }
int LeafCount(BiTree T) { if (T == NULL) { return 0; } if (T->lchild == NULL && T->rchild == NULL) { return 1; } if ((T->lchild != NULL && T->rchild == NULL) || T->lchild == NULL && T->rchild != NULL) { return LeafCount(T->lchild) + LeafCount(T->rchild); } return LeafCount(T->lchild) + LeafCount(T->rchild); }
|