测试了好几颗树了,答案都对,但是提交一直说答案错误,这份代码我看了很久,还是不知道哪里有问题,这里附上所有代码,可以直接运行测试
题目
按先序创建二叉树
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 100
typedef struct TNode * BinTree; /* 二叉树类型 */
typedef char ElementType;
struct TNode { /* 树结点定义 */
ElementType Data; /* 结点数据 */
BinTree Left; /* 指向左子树 */
BinTree Right; /* 指向右子树 */
};
int NodeCount(BinTree BT);
int NodeCountN0(BinTree BT);
int NodeCountN1(BinTree BT);
int NodeCountN2(BinTree BT);
//按先序次序输入二叉树中结点的值(一个字符),@表示空树,构造二叉链表表示二叉树T
BinTree CreatBinTree()
{
ElementType ch;
BinTree T;
scanf("%c", &ch); /*按先序次序输入树的结点,空树输入@*/
if (ch == '@')
T = NULL;
else {
T = (BinTree)malloc(sizeof(struct TNode));
T->Data = ch;
T->Left = CreatBinTree();
T->Right = CreatBinTree();
}
return T;
}
int main()
{
BinTree BT;
int count, count0, count1, count2;
BT = CreatBinTree();
if (BT == NULL) {
printf("\n空树!\n");
}
else {
count = NodeCount(BT);
printf("该二叉树中总结点个数为:%d", count);
printf("\n");
count0 = NodeCountN0(BT);
printf("该二叉树中叶子结点个数为:%d", count0);
printf("\n");
count1 = NodeCountN1(BT);
printf("该二叉树中度为1的结点个数为:%d", count1);
printf("\n");
count2 = NodeCountN2(BT);
printf("该二叉树中度为2的结点个数为:%d", count2);
}
return 0;
}
/* 请在这里填写答案 */
//判断一个节点是否为叶子节点
int isNode0(BinTree T) {
if (T == NULL)
return 0;
if (T->Left == NULL && T->Right == NULL)
return 1;
return 0;
}
//判断是否为度为1的节点
int isNode1(BinTree T) {
if (T == NULL)
return 0;
//只有左孩子
if (T->Left != NULL && T->Right == NULL) {
return isNode0(T->Left);
}
//只有右孩子
if (T->Right != NULL && T->Left == NULL) {
return isNode0(T->Right);
}
return 0;
}
//计算总结点个数
int NodeCount(BinTree BT) {
if (BT == NULL)
return 0;
else {
int count = 1;//根节点算一个
count += NodeCount(BT->Left);//加上左子树的总结点个数
count += NodeCount(BT->Right);//加上右子树的总结点个数
return count;
}
}
/*计算二叉树中度为0的结点个数(叶子节点)*/
int NodeCountN0(BinTree BT) {
if (BT == NULL)
return 0;
int count = 0;
if (BT != NULL) {
//访问根节点
if (BT->Left == NULL && BT->Right == NULL)
count++;
//接收左子树的0度节点个数
count += NodeCountN0(BT->Left);
//接收右子树的0度节点数
count += NodeCountN0(BT->Right);
return count;
}
//节点为空返回0
return 0;
}
/*计算二叉树中度为1的结点个数*/
int NodeCountN1(BinTree BT) {
if (BT == NULL)
return 0;
int count = 0;
if (BT != NULL) {
//访问根节点
if (isNode1(BT))
count++;
//接收左子树的1度节点个数
count += NodeCountN1(BT->Left);
//接收右子树的1度节点数
count += NodeCountN1(BT->Right);
return count;
}
//节点为空返回0
return 0;
}
/*计算二叉树中度为2的结点个数*/
int NodeCountN2(BinTree BT) {
if (BT == NULL)
return 0;
int count = 0;
if (BT != NULL) {
//访问根节点
if (BT->Left!=NULL&&BT->Right!=NULL)
count++;
//接收左子树的2度节点个数
count += NodeCountN2(BT->Left);
//接收右子树的2度节点数
count += NodeCountN2(BT->Right);
}
return count;
}