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

凌乱了,二叉树的创建和中序遍历

2013-04-20 
凌乱了,求救,二叉树的创建和中序遍历#includestdio.h#includestring.h#includestdlib.htypedef stru

凌乱了,求救,二叉树的创建和中序遍历

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct NODE
{
int data;
NODE* lchild;
NODE* rchild;
}NODE,*tree;
void creat(tree t)
{
int x;
scanf("%d",&x);
if(x==-1)
t=NULL;
else
{
t=(tree)malloc(sizeof(NODE));
t->data=x;
creat(t->lchild);
creat(t->rchild);

}
}
void mid(tree t)
{
if(t)
{
mid(t->lchild);
printf("%d ",t->data);
mid(t->rchild);

}
}

int main()
{
tree t;
creat (t);
mid(t);
       return 0;
}
二叉树 遍历
[解决办法]
什么错误??都忘了数据结构的内容了
[解决办法]

struct tree
{
   int data;
   struct tree *lchild;
   struct tree *rchild;
};

// 先序建立二叉树
struct tree *create(struct tree *BT,int k)
{
  struct tree *p;
  int x;
  p=(struct tree *)malloc(sizeof(struct tree)); 
  printf("输入结点的整数值(0表示空) : ");
  scanf("%d",&x);
  if(x!=0)
  {
     if(!(p=(struct tree *)malloc(sizeof(struct tree))))
      exit(0);
  //生成主根或子树根
     p->data=x; 
     p->lchild=NULL;
     p->rchild=NULL;
     if(k==0)
      BT=p;
     if(k==1)
       BT->lchild=p;
     if(k==2)
      BT->rchild=p;
     create(p,1);//建立左子树
     create(p,2);//建立右子树
  }
  return(BT);
}
// 先序遍历
int visit(struct tree *BT)
{
  if(BT!=NULL)
    {
      printf("%d ",BT->data);
      visit(BT->lchild);
      visit(BT->rchild);
    }
  return 0;
}

void main()
{
  struct tree *p;
  p=(struct tree *)malloc(sizeof(struct tree));
  p=create(p,0);
  visit(p);
  printf("\n");
}

你那个建立很有问题啊,岂不是要输入很多个-1?
[解决办法]
应该定义成struct NODE *lchild;struct NODE *rchild;这样lchild rchild类型就与结构体一致了,那么就不会报错了,现在就是因为类型不一致

热点排行