二叉树的建立
在数据结构的书里,看了半天,还是没有回过味来,不知其然。
简单的按照书里的意思就是:比如现在有int 1--31,一个数一个数的添加进去,构建成一个二叉树,可是里面的代码和分析我看了半天也没明白。
哪位大虾能给我个有详细文档的代码吗?感激不尽
[解决办法]
输入一串字符,按字母顺序构造一棵二叉排序树,每个结点的值就是一个字符。然后求该树的深度、叶子结点
数,再按中序遍历打印出来。
#include <stdio.h>
#include <malloc.h>
#define Len sizeof(btnode)
#define null 0
/*定义结点*/
typedef struct node{
char data;
struct node *lchild,*rchild;
}btnode;
btnode *T;
/*定义一个插入算法*/
struct node *insert(btnode *s,btnode *t)
{if(t=null)
t=s;
else if(s-> data <t-> data)
t-> lchild=insert(s,t-> lchild);
else t-> rchild=insert(s,t-> rchild);
return t;
}
/*生成一棵二叉树*/
btnode *creat_bintree()
{
char ch;
btnode *t,*s;
printf( "\n enter ch in order: ");
ch=getchar();
if(ch= ' ') t=null;
else{t=(btnode *)malloc(Len);
t-> data=ch;
t-> lchild=null;
t-> rchild=null;
s=insert(s,t);
getchar();
}
return t;
}
/*求二叉树的深度*/
int counth(btnode *t)
{int h,lh,rh;
if(t=null) h=0;
else{h=1;lh=counth(t-> lchild);rh=counth(t-> rchild);
if(lh> rh) h=h+lh;
else h=h+rh;
}
return h;
}
/*求二叉树的叶子结点数*/
int countleaf(btnode *t)
{
int leaf;
if (t=null) leaf=0;
else
if((t-> lchild=null)&&(t-> rchild=null)) leaf=1;
else leaf=countleaf(t-> lchild)+countleaf(t-> rchild);
return leaf;
}
/*中序遍历该树*/
void visit(btnode *t)
{putchar(t-> data);
printf( "\t ");
}
void inorder(btnode *t)
{if (t)
{inorder(t-> lchild);
visit(t);
inorder(t-> rchild);
}
}
int main()
{
int depth,leaf_sum;
btnode *T;
T=creat_bintree();
printf( "\n ");
inorder(T);
printf( "\n ");
depth=counth(T);
printf( "the depth of the tree is %d\n ",depth);
leaf_sum=countleaf(T);
printf( "the number of leaves are:%d\n ",leaf_sum);
return 0;
}