基于二叉链表的二叉树结点个数的统计
描述
设二叉树中每个结点的元素均为一个字符,按先序遍历的顺序建立二叉链表,编写三个递归算法对二叉树的结点(度为0、1、2)个数进行统计。
输入
多组数据。每组数据一行,为二叉树的前序序列(序列中元素为‘0’时,表示该结点为空)。当输入只有一个“0”时,输入结束。
输出
每组数据输出一行,每行三个数分别为二叉树的度为0、1、2的结点个数。每两个数用空格分隔。
输入样例 1
abcd00e00f00ig00h00 abd00e00cf00g00 0
输出样例 1
5 0 4 4 0 3
#include<iostream>
using namespace std;
#define Maxsize 100
typedef struct BiNode {
char data;
BiNode* lchild, * rchild;
}BiNode,*BiTree;
void Create(BiTree& t,char a[],int &i) {//递归建立二叉链树
if (a[i] == '0') {
t = NULL;
}
else {
t = new BiNode;
t->data = a[i];
Create(t->lchild, a, ++i);
Create(t->rchild, a, ++i);
}
}
int zero(BiTree& t) {
if (t==NULL) {
return 0;
}
else if (t->lchild==NULL&&t->rchild==NULL) {
return zero(t->lchild) + zero(t->rchild) + 1;
}
else {
return zero(t->lchild) + zero(t->rchild);
}
}
int one(BiTree& t) {
if (t==NULL) {
return 0;
}
else if ((t->lchild != NULL && t->rchild == NULL) || (t->lchild == NULL && t->rchild != NULL)) {
return one(t->lchild) + one(t->rchild) + 1;
}
else {
return one(t->lchild) + one(t->rchild);
}
}
int two(BiTree& t) {
if (t==NULL) {
return 0;
}
else if (t->lchild != NULL && t->rchild != NULL) {
return two(t->lchild) + two(t->rchild) + 1;
}
else {
return two(t->lchild) + two(t->rchild);
}
}
int main() {
char a[1000];
while (cin>>a&&a[0]!='0') {
int i = -1;
BiTree t;
Create(t, a, ++i);
cout << zero(t) << " " << one(t) << " " << two(t) << endl;
}
return 0;
}