c语言二叉树层次遍历不用队列,关于二叉树的层次遍历问题,求大神帮助

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

#include

#include

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

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。这让我百思不得其解。

因此求大神帮忙

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值