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 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探