数据结构中的树相关编程题

2017(3): 计算并输出树中每个叶子结点的data域值与所在的层数(递归)

void fun(TNode *t,int h){ //t为树结点指针,h为该结点深度
if(t == NULL)
return; //如果该结点为空,直接退出该函数
if(t->firstchild == NULL) //该结点为叶子结点,直接输出
printf("%c %d",t->data,h);
fun(t->firstchild,h+1); //递归查询左子树,深度+1
fun(t->nextsibling,h); //递归查询右子树,深度不变
}
void nodedepth(TNode *Tree){
fun(Tree,1); //Tree为树根,h初始化为1
}


2016(3): 计算树中第i层结点的个数(递归)

void count(TNode *t, int h, int *num){ //t为树结点指针,h为该结点深度,num为记录数组
if(t == NULL)
return; //如果该结点为空,直接退出该函数
num[h]++; //t为非空结点(深度为h),则h的记录+1
fun(t->firstchild,h+1); //递归查询左子树,深度+1
fun(t->nextsibling,h); //递归查询右子树,深度不变
}
void nodenum(TNode *t){
int num[200]={0}; //记录数组(足够大),初始化为0
count(t,1,num); //初始化h为1
for(int i=1; i<200 &&num[i] != 0; i++) //记录数组从1开始输出,且只输出不为0的层次
printf("第%d层:%d个结点",i,num[i]);
}


2015(数据结构(821))(3): 计算树中每个结点的度(递归遍历,单点查询)

int count(TNode *t){ //一个结点的度计算函数,
if(t == NULL || t->firstchild == NULL)
return 0; //空指针返回0,若左子树为NULL则表示该结点无孩子结点,也返回0
int n = 1;
t = t->firstchild; //从第一个孩子开始计数
while(t->nextsibling){ //只要存在兄弟结点,度+1
n++;
t=t->nextsibling;
}
return n;
}
void Travel(TNode *t){
if(t) //如果t不为空
print("%c的度为:%d",t->data,count(t)); //输出改结点的度
if(t->firstchild) //t的firstchild不为空
Travel(t->firstchild); //递归遍历左子树
if(t->nextsibling) //t的nextsibling不为空
Travel(t->nextsibling); //遍历右子树
}


2015(数据结构及程序设计828) (3)求二叉树中叶子结点的数目(递归)

void Travel(TNode *t,int *num){
if(t == NULL)
return ;
if(t->lchild == NULL && t->rchild == NULL)
*num++; //叶子结点数+1
if(t->lchild)
Travel(t->lchild); //递归遍历左子树
if(t->rchild)
Travel(t->rchild); //递归遍历右子树
}

int count(TNode *t){
int num = 0;
Travel(t,&num);
return num;
}


2014(数据结构821) (3)输出二叉树中每个结点的层数

void fun(TNode *t,int h){ //t为树结点指针,h为该结点深度(层数)
if(t == NULL)
return; //如果该结点为空,直接退出该函数
if(t->lchild == NULL && t->rchild == NULL) //该结点为叶子结点,直接输出
printf("%c %d",t->data,h);
fun(t->lchild,h+1); //递归查询左子树,深度+1
fun(t->rchild,h+1); //递归查询右子树,深度+1
}
void nodedepth(TNode *Tree){
fun(Tree,1); //Tree为树根,h初始化为1
}

2013数据结构 (3)计算二叉树中度为1的结点个数

void count(BiNode *t,int *num){
if(t == NULL)
return ;
if((t->rchild==NULL && t-lchild!=NULL) || (t->rchild!=NULL && t->lchild==NULL))
*num++; //左右子树中只有一个存在,及度为1,num+1
count(t->lchild,num);
count(t->rchild,num);
}
int countD(BiNode *t){
int num = 0;
count(t,&num);
return num;
}


2012数据结构: (2)建树
BiTree Create(ElemType A[],int i){ //此处的i为下标
if(i > n)
return NULL; //下标超界,返回NULL
BiNode *p = (BiNode *)malloc(sizeof(BINode));
p->data = A[i];
p->lchild = Create(A,2*i);
p->rchild = Create(A,2*i+1);
return p;
}

2011数据结构: (2)二叉排序树,按递减次序打印结点值
typedef struct TNode{
int data;
TNode *lchild,*rchild;
} TNode;
void Travel(TNode *t, int *stack, int &top){ //t为树结点指针,stack为数组首地址,top为栈顶指针
//二叉排序树,左子树都比树根小,右边都比树根大,中序遍历得到由小到大的数列
if(t == NULL)
return ;
//递归中序遍历
Travel(t->lchild);
stack[top++] = t->data; //压栈
Travel(t->rchild);
}
void fun(TNode *t){
int stack[200]; //stack足够大
int top = 0; //top为栈顶指针,初始化为0
Travel(t,stack,top);
while(top > 0){
printf("%d ",stack[top]); //出栈(输出)
}
}

原文地址:https://www.cnblogs.com/ewitt/p/11910160.html