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

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 09:08
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
    张十五 2022-05-12 09:12

    
    BiTree CreateBiTree() {
        int a = 0;
        BiTree T = NULL;
        scanf("%d", &a);
        if (a != 0)
        {
            T = (BiTree)malloc(sizeof(BiNode));
            T->data = a;
            T->lchild=CreateBiTree();
            T->rchild=CreateBiTree();
            return T;
        }
    }
    
    
    //主函数里
    BiTree T =  CreateBiTree();
    

    回复
    张十五 2022-05-12 09:16

    2,和上一个一样,队列建的也与问题。
    3.不是C吗,参数里面怎么还有&呢?直接传指针就可以了。

    回复
    张十五 2022-05-12 09:27

    如果只是求最宽度,建个大数组,然后可以带着当前深度的遍历(不管哪种),当前层节点个数++,便利数组求最大值,即可

    回复
    展开全部5条评论
编辑
预览

报告相同问题?

问题事件

  • 系统已结题 5月26日
  • 已采纳回答 5月19日
  • 创建了问题 5月12日
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部