数据结构实验之二叉树三:统计叶子数

来源:互联网 发布:b2b2c php开源 编辑:程序博客网 时间:2024/05/17 02:09

数据结构实验之二叉树三:统计叶子数

Problem Description

已知二叉树的一个按先序遍历输入的字符序列,如abc,,de,g,,f,,, (其中,表示空结点)。请建立二叉树并求二叉树的叶子结点个数。

Input

连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。

Output

输出二叉树的叶子结点个数。

Example Input

abc,,de,g,,f,,,

Example Output

3
-----------------------------------------------------------------------------------------------------------------------------
#include <stdio.h>#include <string.h>#include <stdlib.h>typedef struct node{    char data;    struct node *lchild, *rchild;}*bitTree;int cnt = 0;char str[100];int count = 0;void creatTree(bitTree &root, char str[]){    char ch = str[cnt++];    if(ch == ','){        root = NULL;    }    else{        root = new node;        root->data = ch;        creatTree(root->lchild, str);        creatTree(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;        creatTree(root, str);        printf("%d\n", getnum(root));    }    return 0;}



阅读全文
0 0
原创粉丝点击