首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

关于树的层序遍历有关问题的一个程序异常

2012-03-27 
关于树的层序遍历问题的一个程序错误?#include stdio.h #defineNULL0#defineMAX100structqueue*Qstruct

关于树的层序遍历问题的一个程序错误?
#include "stdio.h "
#define   NULL   0
#define   MAX   100
struct   queue   *Q;

struct   Node
{   int   data;
    struct   Node   *lchild,*rchild;
};

typedef   struct   Node   ElemType;

struct   list
{   ElemType   *data;
    struct   list   *next;
};

struct   queue
{   struct   list   *front,*rear;
    int   count;
};

void   push(ElemType   *node)
{   struct   list   *pnew,*p1,*p2;
    pnew-> data=node;
    pnew-> next=NULL;
    if(Q-> count==0)       Q-> front=pnew;
    else       {   for(p1=Q-> rear;p1-> next!=NULL;)
        {   p2=p1;p1=p1-> next;}
    if(p1==Q-> rear)       Q-> rear=pnew;
    else   p1-> next=pnew;
    }
    Q-> count++;
}

ElemType   *pop()
{     struct   list   *pDel;
      ElemType   *temp;
      if(Q-> count==1)       Q-> rear   =NULL;
      pDel=Q-> front;
      temp=pDel-> data;
      Q-> front=Q-> rear;
      Q-> front-> next=NULL;
      Q-> rear=Q-> rear-> next;
      Q-> count--;
      return   temp;
}

ElemType   *creatnode()
{   ElemType   *pnode;
    pnode=(ElemType   *)malloc(sizeof(ElemType));
    scanf( "%d ",&pnode-> data);
    if(!pnode-> data)         pnode=NULL;
    return   pnode;
}

ElemType   *creatTree(ElemType   *head)
{   head=creatnode();
      if(head)
              {head-> lchild=creatTree(head-> lchild);
  head-> rchild=creatTree(head-> rchild);
}
      return(head);
}

void   printTree(ElemType   *head)
{       while   (head!=   NULL)
              {   printf( "%d ",head-> data);
if   (head-> lchild!=   NULL)
        push   (head-> lchild);
if   (head-> rchild!=   NULL)
      push(head-> rchild);
if   (Q-> count   !=   0)
      printTree(pop());
else       return;
              }
}

void   initi()
{     Q-> front=Q-> rear=NULL;
      Q-> count=0;
}

main()
{   ElemType   *boot=NULL;
    initi();
      boot=creatTree(boot);
        printTree(boot);
          printf( "\n ");
              getch();
}


这是我改过的程序,编译没有错了,可是运行时却出现了死循环,问题出在哪里?

[解决办法]
你的程序在初期建立这个树的时候,退出递归的条件是节点的值为0


在scanf前多printf一句提示信息吧,这样你至少知道你的程序要让你干什么。

push函数也有问题
void push(ElemType *node)
{ struct list *pnew,*p1,*p2;
pnew-> data=node; <-------------------- pnew没有申请内存
pnew-> next=NULL;
if(Q-> count==0) Q-> front=pnew;
else { for(p1=Q-> rear;p1-> next!=NULL;)
{ p2=p1;p1=p1-> next;}
if(p1==Q-> rear) Q-> rear=pnew;
else p1-> next=pnew;
}
Q-> count++;
}

建议你分步调试,光看程序的话,有点不方便

热点排行