求助,求树中叶子结点的个数以及树t中结点值为x的结点的层号

好菜的人 2020-05-14 10:05:29
#include <stdlib.h>
#include <malloc.h>
#define m 3
#define MAXLEN 20

typedef char datatype;
typedef struct node {
datatype data;
struct node *child[m];
} node;
typedef node *tree;

tree CreateTree(); /*按前序遍历顺序建立一棵3度树,返回树根地址 */
int LeafNodes(tree t); /* 求树t中叶子结点的个数,返回值为叶子结点个数*/
int Level(tree t,datatype x,int h);
/* 求树t中结点值为x的结点的层号,h为辅助参数,记录树t的层号,
返回值为结点值为x的结点层号,假设根结点的层号为1。
若树t中不存在结点值为x的结点,返回0*/

int main()
{
int N,level;
datatype ch;
tree t;
t=CreateTree();
printf("\nthe LeafNodes is:%d\n",LeafNodes(t));
scanf("%d",&N);getchar();
while(N--){
scanf("%c",&ch);getchar();
level=Level(t,ch,1);
if (level==0) printf("the node %c is not exist.\n",ch);
else printf("the level of the node %c is %d\n",ch,level);
}
return 0;
}
tree CreateTree()
{
int i;
char ch;
tree t;
if ((ch=getchar())=='#') t=NULL;
else{
t=(tree) malloc (sizeof(node));
t->data=ch;
for (i=0;i<m;++i)
t->child[i]= CreateTree();
}
return t;
}
int LeafNodes(tree t)
{
int n=0;
if(t==NULL) return 0;
else if(t->child[0]==NULL) return 1;
else
{
for(int i=0;i<m;i++)
n+=LeafNodes(t->child[i]);
return n;
}
}
int Level(tree t,datatype x,int h)
{
int a=0,i;
if(t==NULL) return 0;
else
{
if(t->data==x) return 1;
else{
h++;
for(i=0;i<m;i++)
if(t->child[i]==x) a=1;
a=Level(t->child,x,h);
if(a==1) return h;
else return 0;
}
}
}

大佬们帮我看看第二个求层数的怎么写呢?,用递归的思想;;;!
...全文
170 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
Moxixis 2021-05-10
  • 打赏
  • 举报
回复

int Level(tree t,datatype x,int h)
{
    if(t)
    {
        if(t->data==x) return h;
        else
            return Level(t->child[0],x,h+1)+Level(t->child[1],x,h+1)+Level(t->child[2],x,h+1);
    }
    else return 0;
}
非本人所写,搬运工罢了。 原作者:https://blog.csdn.net/qq_51602939/article/details/116197124
好菜的人 2020-05-14
  • 打赏
  • 举报
回复
第二个函数,没有思路,递归好难啊。。

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧