数据结构--二叉树--带你走进C的世界
Welcome to my world
关于二叉树的实现问题,需要对递归有较深的理解,代码中的代码注释段去掉后,可以实现更多功能。希望能从小白的代码中有所收获。当然也希望有新想法可以交流。
代码的测试环境
Dev-C++,VC++6.0,Codeblock…
Ps:如果使用Codeblock,需要对编译环境做一定的调整。不同的测试环境,对代码是一个考验,codeblock的编译环境有一定的不足。运行递归程序易识别不出,导致程序崩溃。以下是有关改进codeblock编译环境的相关链接
https://blog.csdn.net/pxiaozi/article/details/105345346
/*------------------------------------
* 二叉树实现
* Auther:FXZ
*contain: Create_tree
Deepth_tree
Leaf_tree
Parent
Leftbrother
Leftchild
Preorder_tree
Inorder_tree
Postorder_tree
Levelorder_tree
*/
#include<stdio.h>
#include<stdlib.h>
#define visit(name,data,descript) printf("根%d的%s的值是 %d\n",descript,name,data)
#define visit_1(data) printf("%d ",data)
#define OK 0
#define ERROR -1
#define OVERFLOW -2
//----------------------基础部分---------------------------
typedef int Elemtype;
typedef struct tree{
Elemtype data;
struct tree *lchild,*rchild;
}*Tree;
//创建二叉树--递归
/*难点:1.出口条件 ---结尾值为空
2.如何结束 ---递归有出口条件就能停止,保证输入的值足够
3.返回类型 ---递归存在反复调用,返回值类型为输入类型
输值举例 1 6 3 0 9 0 0 2 0 0 4 0 5 0 7 0 0 ---0表示空
二叉树示意图: 1
/ \
6 4
/ \ \
3 2 5
\ \
9 7
*/
Tree Create_tree(Tree &T){
//先序建表
Elemtype c;
scanf("%d",&c);
if(c == 0){
//出口条件,若为0,则T为lNULL
T = NULL;
}else{
if(!(T = (Tree)malloc(sizeof(Tree))))exit(OVERFLOW);
T->data = c;
Create_tree(T->lchild);
Create_tree(T->rchild);
}//if
return T;
}//Cre-tree
//获取树的深度
int Deepth_tree(Tree L){
int i =0, j = 0;
if(!L) return 0;
if(L->lchild) {
i = Deepth_tree(L->lchild);
// printf("i值为%d \n",i);
}//if
if(L->rchild){
j = Deepth_tree(L->rchild);
// printf("j值为%d \n",j);
} //if
return i > j ? i+1 : j+1 ;
}//Deepth
//计算叶子数
int count = 0;
int Leaf_tree(Tree L){
if(L)</