关于二叉树的层次遍历问题,求大神帮助
c语言吧
全部回复
仅看楼主
level 7
x6988312 楼主
#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。这让我百思不得其解。
因此求大神帮忙
2013年05月29日 05点05分 1
level 7
x6988312 楼主
求大神帮助
2013年05月29日 05点05分 2
level 7
x6988312 楼主
新人求助。解决了的必粉
2013年05月29日 06点05分 3
level 8
struct node *root=NULL;
*root=head->stack[0];
root指针的值是NULL,那么下一条语句不是把head->stack[0]写到地址0里去了吗?
小可是自觉的C,不知道你们书上是怎么说的,但根据我的理解,似乎栈的元素应该是字符,通过栈来构造二叉树。最先输入的字符在栈顶,从栈开始,遇到字母建立根结点,出栈,遇到“(”建立左子树,遇到字母放入左子树,出栈,遇到“,”建立右子树,出栈,遇到字母放入右子树,出栈,遇到“)”,出栈,并把上一个“(”也出栈。在应当遇到字母的地方不是字母则对应的子树置空……这样直到栈全空,就完成了树的建立。函数返回树的根结点。
2013年05月29日 06点05分 4
非常感谢,已粉
2013年05月29日 11点05分
1