本题代码如下
int num(tree t)
{if (!t)return 0;else if ((t->lchild && t->rchild==NULL)|| (t->lchild==NULL&& t->rchild))//计算单支树return num(t->lchild) + num(t->rchild) + 1;else return num(t->lchild) + num(t->rchild);
}
完整测试代码如下
#include<stdio.h>
#include<stdlib.h>
typedef struct treenode {char data;struct treenode* lchild, * rchild;
}treenode, * tree;
void buildtree(tree* t)//建树
{char ch;ch = getchar();if (ch == '#')t = NULL;else{*t = (treenode*)malloc(sizeof(treenode));//分配空间(*t)->data = ch;(*t)->lchild = NULL;(*t)->rchild = NULL;buildtree(&((*t)->lchild));buildtree(&((*t)->rchild));}
}
int num(tree t)
{if (!t)return 0;else if ((t->lchild && t->rchild==NULL)|| (t->lchild==NULL&& t->rchild))//计算单支树return num(t->lchild) + num(t->rchild) + 1;else return num(t->lchild) + num(t->rchild);
}
int main() {tree t;buildtree(&t);printf("该二叉树中有%d个单分支\n", num(t));return 0;
}
测试:ABD##E##CF###
/* A
B C
D E F
*/