weixin_70701961 2022-05-12 16:07 采纳率: 62.5%
浏览 74
已结题

c语言求二叉树宽度,运行以后输入后不能打印

#include<stdio.h>
#include<stdlib.h>

//定义二叉树
typedef struct BiNode{
int data;
struct BiNode *lchild,*rchild;
}BiNode,*BiTree;

//创建二叉树
void CreateBiTree(BiTree T){
int a;
scanf("%d",&a);
if(a==0)
T=NULL;
else{
T=(BiTree)malloc(sizeof(BiNode));
T->data=a;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}

//定义队列
typedef struct Qnode{
BiTree data;
struct Qnode *next;
}Qnode,*QuenePtr;
typedef struct{
QuenePtr front;
QuenePtr rear;
}LinkQueue;

//队列初始化
void InitQueue(LinkQueue &Q){
Q.front=Q.rear=(QuenePtr)malloc(sizeof(Qnode));
Q.front->next=NULL;
}

//入队
void EnQueue(LinkQueue &Q,BiTree T){
QuenePtr p;
p=(QuenePtr)malloc(sizeof(Qnode));
p->data=T;
p->next=NULL;
Q.rear->next=p;
Q.rear=p;
}

//出队
void DeQueue(LinkQueue &Q){
QuenePtr p;
if(Q.front!=Q.rear){
p=Q.front;
Q.front->next=p->next;
free(p);
}
}

//求队列长度
int length(LinkQueue &Q){
int len=0;
QuenePtr p;
p=Q.front->next;
while(p){
len++;
p=p->next;
}
return len;
}

//求二叉树宽度
int maxwidth(BiTree T){
int len,width=0;
LinkQueue Q;
InitQueue(Q);
QuenePtr p;
BiTree T1;
p=(QuenePtr)malloc(sizeof(Qnode));
InitQueue(Q);
if(T->lchild){
EnQueue(Q,T->lchild);
}
if(T->rchild){
EnQueue(Q,T->rchild);
}
width=len=length(Q);
p=Q.front;
while(p){
T1=p->data;
if(T1->lchild){
EnQueue(Q,T1->lchild);
}
if(T1->rchild){
EnQueue(Q,T1->rchild);
}
DeQueue(Q);
len--;
if(len==0){
len=length(Q);
width=width>len?width:len;
}
p=Q.front;
}
return width;
}

//主函数
int main(){
int width;
BiTree T;
CreateBiTree(T);
width=maxwidth(T);
printf("%d",width);
return 0;
}

  • 写回答

1条回答 默认 最新

  • 张十五 2022-05-12 17:08
    关注

    第一个问题 : 创建有问题,创建出来的树没有给T(无法)赋值。传指针的本质是传地址,T的指向没有变,所以没有树。
    3种办法,1.二级指针,2创建出来的节点作为返回值返回出来,3.初始化一个根节点,从他的叶子开始建

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 5月27日
  • 已采纳回答 5月19日
  • 创建了问题 5月12日

悬赏问题

  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景