第9关:基于二叉链表的二叉树结点个数的统计
任务描述
设二叉树中每个结点的元素均为一个字符,按先序遍历的顺序建立二叉链表,编写三个递归算法对二叉树的结点(度为0、1、2)个数进行统计。
编程要求
输入
多组数据。每组数据一行,为二叉树的前序序列(序列中元素为‘0’时,表示该结点为空)。当输入只有一个“0”时,输入结束。
输出
每组数据输出一行,每行三个数分别为二叉树的度为0、1、2的结点个数。每两个数用空格分隔。
测试说明
平台会对你编写的代码进行测试:
测试输入:
abcd00e00f00ig00h00
abd00e00cf00g00
0
预期输出:
5 0 4
4 0 3
C++代码:
270.h
#include<iostream>
#include<string.h>
using namespace std;
typedef struct BiTNode
{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
void CreateBiTree(BiTree &T,char S[],int &i)
{
//先序建立二叉树
if(S[i]=='0')
T=NULL;
else
{
T=new BiTNode;
T->data=S[i];
CreateBiTree(T->lchild,S,++i);
CreateBiTree(T->rchild,S,++i);
}
}
void Count(BiTree T,int &a,int &b,int &c)
{
//二叉树结点个数的统计
if(T==NULL) return;
if(T->lchild&&T->rchild) c++;
else if(T->lchild||T->rchild) b++;
else a++;
Count(T->rchild,a,b,c);
Count(T->lchild,a,b,c);
}
主函数文件不可编辑:
#include<iostream>
#include<string.h>
#include "270.h"
using namespace std;
int a,b,c;//a、b、c分别表示度为0、1、2的结点个数
int main()
{
char S[100];
while(cin>>S)
{
if(strcmp(S,"0")==0) break;
a=b=c=0;
int i=-1;
BiTree T;
CreateBiTree(T,S,++i);
Count(T,a,b,c);
cout<<a<<" "<<b<<" "<<c<<endl;
}
return 0;
}
第10关:基于二叉链表的二叉树高度的计算
任务描述
设二叉树中每个结点的元素均为一个字符,按先序遍历的顺序建立二叉链表,,编写递归算法计算二叉树的高度。
编程要求
输入
多组数据。每组数据一行,为二叉树的前序序列(序列中元素为‘0’时,表示该结点为空)。当输入只有一个“0”时,输入结束。
输出
每组数据分别输出一行,为二叉树的高度。
测试说明
平台会对你编写的代码进行测试:
测试输入:
abcd00e00f00ig00h00
abd00e00cf00g00
0
预期输出:
4
3
C++代码:
271.h:
#include<iostream>
#include <string.h>
using namespace std;
typedef struct BiTNode
{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
void CreateBiTree(BiTree &T,char S[],int &i)
{
//先序建立二叉树
if(S[i]=='0')
T=NULL;
else
{
T=new BiTNode;
T->data=S[i];
CreateBiTree(T->lchild,S,++i);
CreateBiTree(T->rchild,S,++i);
}
}
int Depth(BiTree T)
{
//二叉树高度的计算
int deep;
int ldeepth,rdeepth;
if(T==NULL) return 0;
else{
ldeepth=Depth(T->lchild);
rdeepth=Depth(T->rchild);
deep=ldeepth>=rdeepth?ldeepth+1:rdeepth+1;
}
return deep;
}
主函数文件不可编辑:
#include<iostream>
#include "271.h"
#include <string.h>
using namespace std;
int main()
{
char S[100];
while(cin>>S)
{
if(strcmp(S,"0")==0) break;
int i=-1;
BiTree T;
CreateBiTree(T,S,++i);
cout<<Depth(T)<<endl;
}
return 0;
}