【数据结构】二叉树详解(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 递归流程图:


相关推荐
西岸行者6 天前
学习笔记:SKILLS 能帮助更好的vibe coding
笔记·学习
琢磨先生David6 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
悠哉悠哉愿意6 天前
【单片机学习笔记】串口、超声波、NE555的同时使用
笔记·单片机·学习
qq_454245036 天前
基于组件与行为的树状节点系统
数据结构·c#
超级大福宝6 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
别催小唐敲代码6 天前
嵌入式学习路线
学习
岛雨QA6 天前
常用十种算法「Java数据结构与算法学习笔记13」
数据结构·算法
weiabc6 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
wefg16 天前
【算法】单调栈和单调队列
数据结构·算法
岛雨QA6 天前
图「Java数据结构与算法学习笔记12」
数据结构·算法