大学程序实验.数据结构.树型结构及其应用四.算子树数


0 目录

4 树型结构及其应用

4.4 算子树数

4.4.1 题目

编写算法求二叉树中某个结点的子孙结点(不包括该结点)为多少个。

4.4.2 源码

// 算子树数.cpp : Defines the entry point for the console application.
//
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "malloc.h"

#define OK 1
#define ERROR 1

typedef int Status;
typedef char TElemType;

typedef struct BiTNode
{
TElemType data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;


void BiTreeMenu();
Status CreateBiTree(BiTree *T);
Status DescNumCount(BiTree T,int &DescNum);
BiTree PreOrderLOC(BiTree T,TElemType e);


void BiTreeMenu()
{
printf("========算子孙结点算法========\n");
printf("二叉树创建\n");
printf("请输入二叉树各节点数:");
}

Status CreateBiTree(BiTree *T)
{
TElemType ch;
TElemType temp;

scanf("%c",&ch);
temp=getchar();

if(ch == '#')
{
*T = NULL;
}
else
{
*T=(BiTree)malloc(sizeof(BiTNode) );
if(!(*T))
{
return ERROR;
}
else
{
(*T)->data=ch;
printf("请输入%c的左节点的值:",ch);
CreateBiTree(&(*T)->lchild);

printf("请输入%c的右节点的值:",ch);
CreateBiTree(&(*T)->rchild);
}
}
return OK;
}

Status DescNumCount(BiTree T,int &DescNum)
{
if(!T)
{
return ERROR;
}

if(T->lchild)
{
DescNum++;
}
if(T->rchild)
{
DescNum++;
}

DescNumCount(T->lchild,DescNum);
DescNumCount(T->rchild,DescNum);

return DescNum;
}

BiTree PreOrderLOC(BiTree T,TElemType e)
{
if(!T)
{
return NULL;
}

if(T->data == e)
{
return T;
}

BiTree pTNode = PreOrderLOC(T->lchild,e);
if (pTNode)
{
return pTNode;
}

pTNode = PreOrderLOC(T->rchild,e);
if (pTNode)
{
return pTNode;
}
else
{
return NULL;
}
}

Status main()
{
int DescNum=0;
TElemType value;
BiTree pRoot;
BiTree *p=(BiTree*)malloc(sizeof(BiTree));

BiTreeMenu();
printf("请输入第一个节点的值,'#'代表没有叶节点:\n");
CreateBiTree(&pRoot);

printf("\n");
printf("请输入你要计算子孙的结点:");
scanf("%c",&value);
pRoot = PreOrderLOC(pRoot,value);
DescNum = DescNumCount(pRoot,DescNum);

printf("该节点的子孙结点个数为:");
printf("%d",DescNum);
printf("\n");

return OK;
}

1.1.3 下载

链接地址: ​​4.4_算子树数.CPP​