时间限制:1000MS 代码长度限制:10KB
题型: 编程题 语言: G++;GCC
Description
构造二叉链表表示的二叉树:按先序次序输入二叉树中结点的值(一个字符),’#'字符表示空树,构造二叉链表表示的二叉树T,并求此二叉树中度为2的节点总数,度为1的节点总数,度为0的节点总数
#include “stdio.h”
#include “malloc.h”
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
typedef char ElemType;
typedef struct BiTNode{
ElemType data;
struct BiTNode *lchild,*rchild;//左右孩子指针
} BiTNode,*BiTree;
Status CreateBiTree(BiTree &T) { // 算法6.4
// 按先序次序输入二叉树中结点的值(一个字符),’#’字符表示空树,
// 构造二叉链表表示的二叉树T。
char ch;
scanf("%c",&ch);
if (ch==’#’) T = NULL;
else {
if (!(T = (BiTNode *)malloc(sizeof(BiTNode)))) return ERROR;
________________________ // 生成根结点
_______________________ // 构造左子树
_________________________ // 构造右子树
}
return OK;
} // CreateBiTree
int main() //主函数
{
//补充代码
}//main
输入格式
第一行输入先序次序二叉树中结点
输出格式
第一行输出度为2的节点数
第二行输出度为1的节点数
第三行输出度为0的节点数
输入样例
ABC###D##
输出样例
1
1
2
代码如下:
#include <iostream>
#define OK 1
#define ERROR 0
using namespace std;
typedef int Status;
typedef char ElemType;
typedef struct BiTNode
{
ElemType data;
struct BiTNode *lchild,*rchild;//左右孩子指针
}BiTNode,*BiTree;
Status CreateBiTree(BiTree &T)
{
char ch;
scanf("%c",&ch);
if (ch=='#') T = NULL;
else
{
T=new BiTNode;
T->data=ch; // 生成根结点
CreateBiTree(T->lchild); // 构造左子树
CreateBiTree(T->rchild); // 构造右子树
}
return OK;
} // CreateBiTree
int count0=0,count1=0,count2=0;
void count(BiTree T)
{
if(T==NULL) return ;
if(T->lchild==NULL&&T->rchild==NULL) count0++;//出度为0
else if(T->rchild==NULL&&T->lchild!=NULL||T->lchild==NULL&&T->rchild!=NULL)//出度为1
count1++;
else count2++;//出度为2
count(T->lchild);
count(T->rchild);
}
int main()
{
int n;
cin>>n;
BiTree T;
CreateBiTree(T);
count(T);
cout<<count2<<endl<<count1<<endl<<count0<<endl;
return 0;
}