数据结构实验之二叉树三:统计叶子数
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
已知二叉树的一个按先序遍历输入的字符序列,如abc,,de,g,,f,,, (其中,表示空结点)。请建立二叉树并求二叉树的叶子结点个数。
Input
连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。
Output
输出二叉树的叶子结点个数。
Example Input
abc,,de,g,,f,,,
Example Output
二叉树叶子的概念也就是左孩子和右孩子都为空,在遍历的过程中判断一下是否符合这个条件即可。
#include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct node{ //开始此处没有加typedef,就没有定义树这种类型,所以会出现variable or field‘createTree’ declared void这种错误 char data; struct node *lchild, *rchild; }*bitTree; int cnt = 0; char str[100]; int count = 0; void createTree(bitTree &root, char str[]){ char ch = str[cnt++]; if(ch == ',') root = NULL; else { root = new node; root->data = ch; createTree(root->lchild, str); createTree(root->rchild, str); } } int getnum(bitTree &root) { if (root != NULL) { if (root -> lchild == NULL && root -> rchild == NULL) count ++; else { getnum(root -> lchild); getnum(root -> rchild); } } return count; } int main(){ while(~scanf("%s", str)){ cnt = 0; count = 0; bitTree root; createTree(root, str); printf("%d\n", getnum(root)); } return 0; }