x6988312 x6988312
关注数: 1 粉丝数: 20 发帖数: 312 关注贴吧数: 8
关于二叉树的层次遍历问题,求大神帮助 #include<stdio.h> #include<stdlib.h> struct node{ char data; struct node *lchild,*rchild; }; struct stacks{ struct node stack[50]; int top; int length; }; struct stacks *creattree(){/*创建二叉树*/ int flag=1,i; char c=NULL; struct stacks *put; struct node *p=NULL; put=(struct stacks *)malloc(sizeof(struct stacks)); put->top=-1; put->length=0; printf("please input a generalizde list\n"); while(c!='\n'){ scanf("%c",&c); if(c=='('){ put->top++; put->stack[put->top]=*p; flag=1; } else if(c==')') put->top--; else if(c==',') flag=2; else if(c=='\n') break; else{ p=(struct node *)malloc(sizeof(struct node)); p->lchild=NULL; p->rchild=NULL; p->data=c; put->length++; if(put->length!=0){ if(flag==1) (put->stack[put->top]).lchild=p; else if(flag==2) (put->stack[put->top]).rchild=p; } } } return put; } void overtree(struct node *root,int length){/*按层次遍历二叉树*/ struct node list[50]; int top=0,i=0; list[top]=*root; printf("the list is:\n"); printf("%c ",root->data); while(i<length){ if(list[i].lchild!=NULL){ top++; list[top]=*(list[i].lchild); printf("%c ",list[top].data); } if(list[i].rchild!=NULL){ top++; list[top]=*(list[i].rchild); printf("%c ",list[top].data); } i++; } } void main(){ struct node *root=NULL; struct stacks *head; clrscr(); head=creattree(); *root=head->stack[0]; overtree(root,head->length); printf("\nthe numbers of list is:%d ",head->length); free(head); getch(); } 这个程序是输入一个二叉树的广义表,然后建立二叉树。再按层次遍历。 然而,我却出错了,比如说输入a(b,c(d,e))最后得到的结果应该是a b c d e但是得不到。 经过我的检查,发现:在创建树的函数中,c的左右孩子为d,e;但回到了主程序里c的左右孩子竟然都成了a。这让我百思不得其解。 因此求大神帮忙
1 下一页