当前位置:网站首页>[LeetCode]剑指 Offer 55 - I. 二叉树的深度
[LeetCode]剑指 Offer 55 - I. 二叉树的深度
2022-08-02 15:41:00 【Spring-_-Bear】
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
提示:
节点总数 <= 10000
题解一:
/** * 剑指 Offer 55 - I. 二叉树的深度 * 树的深度优先遍历 */
public int maxDepth(TreeNode root) {
return root == null ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
题解二:
/** * 剑指 Offer 55 - I. 二叉树的深度 * 树的广度优先遍历(层次遍历) */
public int maxDepth(TreeNode root) {
if (root == null) {
return depth;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int depth = 0;
// 当队列不为空时遍历
while (!queue.isEmpty()) {
// 遍历当前层的所有元素
for (int i = queue.size(); i > 0; i--) {
TreeNode node = queue.poll();
// 将当前节点的左右孩子加到队尾
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
depth++;
}
return depth;
}
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/er-cha-shu-de-shen-du-lcof
边栏推荐
猜你喜欢
随机推荐
JZ69 跳台阶
WWW'22 推荐系统论文之图神经网络篇
【[SCOI2005] 互不侵犯】【状压DP(含概念讲解)】
UnicodeEncodeError: 'gbk' codec can't encode character '\u2022' in position 178: illegal multibyte s
synchronized已经不在臃肿了,放下对他的成见之初识轻量级锁
SIGIR'22 推荐系统论文之POI篇
数仓:金融级数仓架构转型的最佳实践(下篇)
ICML/ICLR'22 推荐系统论文梳理
提高测试覆盖率的四大步骤
2.4 - 三态模型
怒写400篇AI文章!这群妹子卷疯了…
NC22 合并两个有序的数组
Qt | 关于QPalette的使用
CWE4.8: The 25 most damaging software security issues in 2022
uWSGI看这几篇就够了
Go-5-简单介绍fmt库
MySQL-1-环境部署
助力疫情防控,30行代码就能搞定无服务器实时健康码识别!
Why do I no longer recommend the enumeration strategy pattern?
【[USACO12MAR]Cows in a Skyscraper G】【状压DP && DFS】