C语言创建二叉树过程中遇到的一些问题
2015-12-31 16:35
525 查看
其实这些问题以前也遇到过,不过没总结,遇到又要搞段时间,现在总结下。
比如我们要创建颗如下二叉树,按前序输入,则为AB#D##C##:
开始代码写成下面这样:
#define TElemType char typedef struct BiTNode { TElemType data; struct BiTNode *lchild,*rchild; }BiTNode,*BiTree; void CreateBiTree(BiTree T) { TElemType ch; scanf("%c",&ch); if(ch == '#') { T = NULL; } else { T = (BiTree)malloc(sizeof(BiTNode)); T->data = ch; CreateBiTree(T->lchild); CreateBiTree(T->rchild); return T; } }
其实这种错误和下面这种a,b无法被交换本质上是一样的,只是int类型变成了结构体指针类型:
#include<stdio.h> void swap(int a,int b) { int temp = a; a = b; b = temp; } int main() { int a = 3,b = 4; swap(a,b); printf("%d %d\n",a,b); }
所以类比两个数交换时的处理方式,自然可以想到用下面这种方式来处理:
void CreateBiTree(BiTree *T) { TElemType ch; scanf("%c",&ch); if(ch == '#') { *T = NULL; } else { *T = (BiTree)malloc(sizeof(BiTNode)); (*T)->data = ch; CreateBiTree(&(*T)->lchild); CreateBiTree(&(*T)->rchild); } }
就是不是传结构体指针的值,而是传结构体指针的指针。
指针的指针不好理解,还有一种处理方式如下所示:
BiTree CreateBiTree() { TElemType ch; scanf("%c",&ch); if(ch == '#') { return NULL; } else { BiTree T = (BiTree)malloc(sizeof(BiTNode)); T->data = ch; T->lchild = CreateBiTree(); T->rchild = CreateBiTree(); return T; } }
我开始写的程序就错在在递归调用的时候没有将返回值赋值给父节点的左右孩子。
最后给个正确的完整代码,并用前序遍历输出了构造的二叉树:
#include<stdio.h>
#include<stdlib.h>
#define TElemType char
typedef struct BiTNode {
TElemType data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
BiTree CreateBiTree() { TElemType ch; scanf("%c",&ch); if(ch == '#') { return NULL; } else { BiTree T = (BiTree)malloc(sizeof(BiTNode)); T->data = ch; T->lchild = CreateBiTree(); T->rchild = CreateBiTree(); return T; } }
void traverse(BiTree r) {
if(r == NULL) {
return;
}
printf("%c",r->data);
traverse(r->lchild);
traverse(r->rchild);
}
int main() {
BiTree root;
root = CreateBiTree();
traverse(root);
printf("\n");
}
如果你要用指针的指针来构建的话完整代码如下:
#include<stdio.h>
#include<stdlib.h>
#define TElemType char
typedef struct BiTNode {
TElemType data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
void CreateBiTree(BiTree *T) { TElemType ch; scanf("%c",&ch); if(ch == '#') { *T = NULL; } else { *T = (BiTree)malloc(sizeof(BiTNode)); (*T)->data = ch; CreateBiTree(&(*T)->lchild); CreateBiTree(&(*T)->rchild); } }
void traverse(BiTree r) {
if(r == NULL) {
return;
}
printf("%c",r->data);
traverse(r->lchild);
traverse(r->rchild);
}
int main() {
BiTree root;
CreateBiTree(&root);
traverse(root);
printf("\n");
}
相关文章推荐
- iOS之C语言基础
- C语言预处理命令总结大全 :宏定义
- 很简单的一个c语言问题switch中用了return
- 对于windows平台下的vs2010下vector数组提示“vector subscript out of range”很头疼
- C语言-关于指针类型的新认识
- c++基础--指针
- 返回局部变量如何避免拷贝:Move semantics and rvalue references in C++11
- C 拆分字符串(strtok,strsep)
- C语言内存对齐总结
- VS2013 C++ 动态链接库的生成
- c语言
- C语言中的函数传递
- C++类中静态变量和静态方法使用介绍
- Something about CPP
- 二叉堆--C语言实现
- C++ 学习路线和看法
- pandas安装若干异常及解决方案总结
- :/coolpigs//Visual Studio 2010 "工具">"选项"中的VC++目录编辑功能已被否决
- c++ typedef使用
- C语言的数据、常量和变量