| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 511 人关注过本帖
标题:关于二叉树的层次遍历问题,求大神帮助
只看楼主 加入收藏
x6988312
Rank: 1
等 级:新手上路
帖 子:46
专家分:5
注 册:2012-3-26
结帖率:100%
收藏
已结贴  问题点数:20 回复次数:1 
关于二叉树的层次遍历问题,求大神帮助
#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。这让我百思不得其解。
因此求大神帮忙
搜索更多相关主题的帖子: 二叉树 please include 
2013-05-29 13:55
hahayezhe
Rank: 15Rank: 15Rank: 15Rank: 15Rank: 15
来 自:湖南张家界
等 级:贵宾
威 望:24
帖 子:1386
专家分:6999
注 册:2010-3-8
收藏
得分:20 
你的程序能够跑起来 就已经是个奇迹了
首先你没有对你的变量进行过初始化,再者你输入的第一个值a(b,c(d,e))
为a于是(put->stack[put->top]).lchild=p;  put->top 是-1啊

*root=head->stack[0]; 你居然给指针赋值。。。

你只有在if(c=='('){
       put->top++;
       put->stack[put->top]=*p;
       flag=1;
    }的时候才把值给栈,请问b和d的值怎么进栈??



2013-05-29 15:22
快速回复:关于二叉树的层次遍历问题,求大神帮助
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.014932 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved