1-2 二叉树求结点数
分数 3
作者 鲁法明
单位 山东科技大学
编写函数计算二叉树中的节点个数。二叉树采用二叉链表存储结构。
函数接口定义:
1
| int NodeCountOfBiTree ( 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
| #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
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 NodeCountOfBiTree ( BiTree T);
int main() { BiTree T; int n; CreateBiTree(T); n= NodeCountOfBiTree(T); printf("%d",n); return 0; }
|
输入样例(注意输入0代表空子树):
输出样例:
我的第一遍答案(错误)
1 2 3 4 5 6 7
| int NodeCountOfBiTree (BiTree T) { if (T == NULL) { return 1; } return 1 + NodeCountOfBiTree(T->lchild) + NodeCountOfBiTree(T->rchild); }
|
- 发现,空树是一个结点都没有,指针所指向的是空,应该return 0;
我的正确答案
1 2 3 4 5 6 7 8
| int NodeCountOfBiTree (BiTree T) { if (T == NULL) { return 0; } else { return 1 + NodeCountOfBiTree(T->lchild) + NodeCountOfBiTree(T->rchild); } }
|