行业知识
LeetCode #104 二叉树的最大深度
2026-10-29 19:04:43
来源:互联网转载
104. 二叉index.php/tags-41973.html" >���的最大深度
题目
二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:3
示例 2:
输入:root = [1,null,2]
输出:2
分析
二叉树的最大深度就是二叉树的最大层数,可以递归遍历二叉树的左子树和右子树,在递归遍历到叶子节点的时候,开始向上返回,每返回一层就+1,取左右子树中的最大值
题解
class Solution { public int maxDepth(TreeNode root) { // 遍历左子树和右子树,每层加1,然后判断大小 // 触底反弹 if(root == null){ return 0; } // 从最底层上来,每层+1 int left = maxDepth(root.left) + 1; int right = maxDepth(root.right) + 1; return Math.max(left, right); }}
下一篇:服务器的租来怎么用?