实现二叉树的简单功能
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//业务结点
typedef struct NODE_ST{
int value;
}node_st;
//二叉树模型
typedef struct D_TREE{
node_st cur;
struct D_TREE *lchild,*rchild;
unsigned int sum;
}d_tree;
//中序遍历
void inOrder(void *Node)
{
d_tree *node = Node;
if(node == NULL)
return;
inOrder(node->lchild);
printf("%d",node->cur.value);
inOrder(node->rchild);
}
//计算叶子数量
void countLeaf(d_tree *node,int *num)
{
if(node != NULL){
if(node->lchild==NULL && node->rchild==NULL)
(*num)++;
if(node->lchild)
countLeaf(node->lchild,num);
if(node->rchild)
countLeaf(node->rchild,num);
}
}
//求树的深度
int Depth(d_tree *node)
{
int depthval = 0;
int depthlef = 0;
int depthrig = 0;
if(node == NULL)
return 0;
if(node->lchild){
depthlef = Depth(node->lchild);
}
if(node->lchild){
depthrig = Depth(node->rchild);
}
depthval = 1 + (depthlef > depthrig ? depthlef:depthrig);
return depthval;
}
//二查树的拷贝
d_tree *copy_tree(d_tree *old)
{
d_tree *NewNode = NULL;
d_tree *NewLp = NULL;
d_tree *NewRp = NULL;
if(old == NULL){
return NULL;
}
NewNode = (d_tree *)malloc(sizeof(d_tree));
NewNode->cur.value = old->cur.value;
if(old->lchild)
NewLp = copy_tree(old->lchild);
else
NewLp = NULL;
if(old->rchild)
NewRp = copy_tree(old->rchild);
else
NewRp = NULL;
NewNode->lchild = NewLp;
NewNode->rchild = NewRp;
return NewNode;
}
//测试主函数
int main()
{
d_tree *node;
int i = 0;
int num = 0;
node = (d_tree *)calloc(5,sizeof(d_tree));
for(i = 0; i<5; i++){
node[i].cur.value = i;
}
node[0].lchild = (d_tree *)&node[1];
node[0].rchild = (d_tree *)&node[2];
node[1].lchild = (d_tree *)&node[3];
node[2].rchild = (d_tree *)&node[4];
//拷贝前的遍历
printf("old tree inOrder:");
inOrder(&node[0]);
printf("\n");
//拷贝后的遍历
d_tree *new;
new = copy_tree(&node[0]);
printf("new tree inOrder:");
inOrder(new);
printf("\n");
//打印叶子数
countLeaf(&node[0],&num);
printf("num %d\n",num);
//打印树的深度
printf("depth %d\n",Depth(new));
return 0;
}
下期将介绍二查树非递归遍历的做法