17121 求二叉树各种节点数 SCAU 数据结构

/*17121 求二叉树各种节点数
时间限制:1000MS  代码长度限制:10KB
提交次数:0 通过次数:0

题型: 编程题   语言: 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 "stdio.h"
#include "malloc.h"
#define TRUE 1
#define FALSE 0
#define OK  1
#define ERROR  0
#define INFEASIBLE -1
#define OVERFLOW -2
int a=0,b=0,c=0;//全局变量
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;
        T->data = ch; // 生成根结点
        CreateBiTree(T->lchild);   // 构造左子树
        CreateBiTree(T->rchild);  // 构造右子树
    }
    return OK;
} // CreateBiTree

void f2(BiTree &T)
{
    if (T==NULL)
        return;
    else
    {
        if (T->lchild!=NULL&&T->rchild != NULL)
            a++;
        f2(T->lchild);
        f2(T->rchild);
    }
}//找度为2的

void f1(BiTree &T)
{
    if (T == NULL)
        return;
    else
    {
        if ((T->lchild != NULL &&T->rchild== NULL) || (T->lchild== NULL &&T->rchild != NULL))
            b++;
        f1(T->lchild);
        f1(T->rchild);
    }
}//找度为1的

void f0(BiTree &T)
{
    if (T== NULL)
        return;
    else
    {
        if ((T->lchild == NULL &&T->rchild == NULL))
            c++;
        f0(T->lchild);
        f0(T->rchild);
    }
}//找度为0的
int main()   //主函数
{
    BiTree  T ;
    CreateBiTree(T);
    //补充代码
    f2(T);
    f1(T);
    f0(T);
    printf("%d\n%d\n%d\n",a,b,c);
}//main

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值