飞行的猪哼哼

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Problem Description

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

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

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

abc,de,g,f,
Sample Output

3
就是把所有节点走一遍找根节点不为空,但是左右子树根节点为空的根的个数。

#include <stdlib.h>
#include <stdio.h>

char a[100];
int n;
int count;
struct node
{
    char data;
    struct node *left;
    struct node *right;
};

struct node *create()
{
    struct node *root;
    if(a[n]==',')
    {
        n++;
        root=NULL;
    }
    else
    {
        root=(struct node *)malloc(sizeof(struct node));
        root->data=a[n];
        n++;
        root->left=create();
        root->right=create();
    }
    return root;
}

void find(struct node *root)
{
  if(root)
  {
      if(!(root->left)&&!(root->right))
      {
          count++;
      }
      find(root->left);
      find(root->right);
  }
}

int main()
{

    while(~scanf("%s",a))
    {
        count=0;
        n=0;
        struct node *root=create();
        find(root);
        printf("%d\n",count);
    }
    return 0;
}


posted on 2018-11-05 12:10  飞行的猪哼哼  阅读(72)  评论(0)    收藏  举报