二叉树的简单操作框架(C语言)

实现二叉树的简单功能

#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;
}

下期将介绍二查树非递归遍历的做法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值