【数据结构】二叉树详解(2)

⭐️ 前言

✨ 往期文章链接:二叉树的概念性质

上一篇我们讲了二叉树的结构定义,以及前序/中序/后序 的递归遍历,还有一些二叉树的接口实现,本篇我们补充一个二叉树的接口 BinaryTreeDepth。✨上一篇文章链接:二叉树详解(1)

前篇:



⭐️二叉树的其他接口

c 复制代码
// 求二叉树的深度
int BinaryTreeDepth(BinaryTreeNode* root);

BinaryTreeDepth 实现:

c 复制代码
int BinaryTreeDepth(BinaryTreeNode* root) {
	// 空树没有高度直接返回0
	if (root == NULL) {
		return 0;
	}
	
	// 递归获取左子树的高度
	int leftTreeDepth = BinaryTreeDepth(root->left);
	// 递归获取右子树的高度
	int rightTreeDepth = BinaryTreeDepth(root->right);

	// 比较左子树和右子树的高度 取较高的同时在加上当前这一层的高度
	return leftTreeDepth > rightTreeDepth ? leftTreeDepth + 1 : rightTreeDepth  + 1;
}

BinaryTreeDepth 递归流程图:


相关推荐
Nan_Shu_6141 小时前
学习SpringBoot
java·spring boot·后端·学习·spring
●VON1 小时前
重生之我在大学自学鸿蒙开发第二天-《MVVM模式》
学习·华为·harmonyos
你真的可爱呀2 小时前
uniapp学习【vue3在uniapp中语法,使用element,使用uView UI】
学习·uni-app
Rubisco..2 小时前
牛客周赛 Round 111
数据结构·c++·算法
2501_916766542 小时前
【Git学习】初识git:简单介绍及安装流程
git·学习
代码小菜鸡6662 小时前
java 常用的一些数据结构
java·数据结构·python
火山灿火山2 小时前
详解AVL树旋转操作实现
数据结构·c++
哈基鑫2 小时前
手写数字识别学习笔记
笔记·学习
im_AMBER2 小时前
Web 开发 29
前端·学习·web
少许极端2 小时前
算法奇妙屋(六)-哈希表
java·数据结构·算法·哈希算法·散列表·排序