数据结构:二叉树基本操作


数据结构:二叉树基本操作


创建 复制 求树深度 求叶子节点个数

本贴借鉴原文章链接 预查看点击此处
建树
× 代表该结点不存在

#include<stdio.h>
#include<stdlib.h>

struct tree{
	int date;
	struct tree* left;
	struct tree* right;
};//结点结构

typedef tree node;
typedef node* ptree;

ptree creatree(int* date,int num) {
	ptree tempT;//临时根节点
	if (date[num] == 0 || num > 15) {
		return NULL;
	}//数据为空或建树完成
	else {
		tempT = (ptree)malloc(sizeof(node));//为新节点申请内存
		tempT->date = date[num];//存储数据
		tempT->left = creatree(date, 2 * num);//递归建左子树
		tempT->right = creatree(date, 2 * num + 1);//递归建右子树
		return tempT;
	}
}

ptree copytree(ptree T) {
	ptree tempT;
	if (T != NULL) {
		tempT = (ptree)malloc(sizeof(node));
		tempT->date = T->date;//根节点复制
		tempT->left = copytree(T->left);//递归复制左子树
		tempT->right = copytree(T->right);//递归复制右子树
		return tempT;
	}
	else
		return NULL;
}

void pribtio(ptree T) {
	//中序遍历二叉树 
	if (T != NULL)
	{
		//遍历左子树
		pribtio(T->left);
		//遍历根节点
		printf("%2d", T->date);
		//遍历右子树
		pribtio(T->right);
	}
}

int depth(ptree T) {//求树的深度 即左右子树深度较大者加一
	static int m=0,n=0;
	if (T != NULL) {
		m = depth(T->left);
		n = depth(T->right);
		if (m > n)
			return m + 1;
		else
			return n + 1;
	}
	else
		return 0;
}

int countnode(ptree T,int & node) {
	if (T == NULL)
		return node;
	else {
		if (T->left == NULL && T->right == NULL)
			node++;
		countnode(T->left, node);
		countnode(T->right, node);
		return node;
	}
}

int main(void){
	ptree T = NULL;
	ptree newT = NULL;
	int deep;

	int nodedate[16] = { 0,5,4,6,2,0,0,8,1,3,0,0,0,0,7,9 };

	T = creatree(nodedate,1);//建树
	printf("中序遍历结果:\n");
	pribtio(T);//中序遍历二叉树

	printf("\n");
	deep=depth(T);
	printf("此二叉树的高度是%d\n",deep);
    
    codenum = countnode(T, codenum);
	printf("叶子结点的个数为%d\n", codenum);

    newT = copytree(T);
	printf("中序遍历复制的二叉树结果:\n");
	pribtio(newT);//中序遍历复制二叉树

	return 0;
}

运行结果如下
运行结果

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值