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;
}