PTA-7-2 度为2的结点个数 (20 分)

7-2 度为2的结点个数 (20 分)

设有一棵二叉树,其结点值为字符型并假设各值互不相等,采用二叉链表存储表示。现输入其扩展二叉树的前序遍历序列,要求建立该二叉树,并求其度为2的结点个数。
输入格式:

第一行为一个整数n,表示以下有n组数据,每组输入一行字符串(字符串长度小于等于20),这个字符串为扩展二叉树的前序遍历序列。
输出格式:

每组输出占一行,输出该二叉树中度为2的结点个数。
输入样例:

在这里给出一组输入。例如:

2
AB#D##C##
ABD##E##C#F##
结尾无空行

输出样例:

在这里给出相应的输出。例如:

1
2
结尾无空行
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct BiNode{
    char data;
    struct BiNode * lchild,* rchild;
}BiNode,*BiTree;
void creat(BiTree *T)
{
    char ch;
    scanf("%c",&ch);
    if(ch=='#')
    {
        *T=NULL;
    }
    else
    {
        *T=(BiTree)malloc(sizeof(BiNode));
        (*T)->data=ch;
        creat(&(*T)->lchild);
        creat(&(*T)->rchild);
    }
    return;
}
int count(BiTree T)
{
    int number=0;
    if(T)
    {
        if(T->lchild&&T->rchild)//当一个顶点都有左孩子和右孩子的时候,它的度为二
        {
            number++;
            number+=count(T->lchild);
            number+=count(T->rchild);
        }
        else{
             number+=count(T->lchild);
            number+=count(T->rchild);
        }
    }
    return number;
}
int main(void)
{
    int n;
    int t;
    scanf("%d",&n);
    while(n--)
    {
    t=0;
    getchar();
    BiTree T;
    creat(&T);
    t=count(T);
    printf("%d\n",t);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值