首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

二叉树的创建与遍历解决办法

2012-03-25 
二叉树的创建与遍历菜鸟上路,刚学习数据结构,在看到二叉树这一章时动手写了下,运行程序结果老不对。比如:我

二叉树的创建与遍历
菜鸟上路,刚学习数据结构,在看到二叉树这一章时动手写了下,运行程序结果老不对。
比如:我输入AB###但是程序老是在运行,CreateBiTree应该结束啊!我把其中的char 换成 int, 判断条件设置为0,程序能够正常结束,但是Display却没有看到任何结果,求大虾指导!!!
#include <stdio.h>
#include <stdlib.h>

typedef char ElemType;

typedef struct Node {
  ElemType data;
  struct Node *lchild, *rchild;
} BiTree;

void CreateBiTree(BiTree *t) {
  ElemType ch;
  scanf("%c", &ch);
  if (ch == '#') {
  t = NULL;
  } else {
  t = (BiTree *) malloc(sizeof (BiTree));
  t->data = ch;
  CreateBiTree(t->lchild);
  CreateBiTree(t->rchild);
  }
}

void Display(BiTree *t) {
  if (t != NULL) {
  printf("%c", t->data);
  Display(t->lchild);
  Display(t->rchild);
  }
}

int main() {

  BiTree *t;
  CreateBiTree(t);
  Display(t);
  return 0;
}

[解决办法]
你的问题很简单,是c语言中典型犯的错误,
你的函数CreateBiTree(bitreex* t)中的形参t是Bitree*型,第一你没有初始化为NULL,有隐患 第二,致命的错误,c语言中是实参复制一份拷贝给形参,函数体中对形参的操作不会影响到实参,也是就你递归折腾了一圈你的实参t的值还是一个你没有初始化的值,根本不是你构建的二叉树的根节点的地址所以我给你改了一下,把CreatBiTree的参数改为bitreex**就oK了,你看一下吧
#include <stdio.h>
#include <stdlib.h>

typedef char ElemType;

typedef struct Node {
ElemType data;
struct Node *lchild, *rchild;
} BiTree;

void CreateBiTree(BiTree **t) {
ElemType ch;
scanf("%c", &ch);
if (ch == '#') {
*t = NULL;
} else {
*t = (BiTree *) malloc(sizeof (BiTree));
(*t)->data = ch;
CreateBiTree(&((*t)->lchild));
CreateBiTree(&((*t)->rchild));
}
}

void Display(BiTree *t) {
if (t != NULL) {
printf("%c", t->data);
Display(t->lchild);
Display(t->rchild);
}
}

int main() {

BiTree *t=NULL;
CreateBiTree(&t);
Display(t);
return 0;
}
[解决办法]
指针进去之后是一个副本,你是为副本分配了内存,而不是main函数中的那个指针。

热点排行