

LeetCode Hot 100:二叉树的最大深度
力扣第 104 题「二叉树的最大深度」要求返回从根节点到最远叶子节点的最长路径上的节点数。示例
[3,9,20,null,null,15,7] 的答案是 3;空树也是合法输入。1 这道题收录在 LeetCode 热题 100 中。递归函数
maxDepth(node) 的返回值是:从当前节点往下的最大层数。节点为空时返回 0;节点不为空时,分别取得左右子树深度,取较大值,再加上当前节点这一层。function maxDepth(root) {
if (root === null) return 0;
const leftDepth = maxDepth(root.left);
const rightDepth = maxDepth(root.right);
return Math.max(leftDepth, rightDepth) + 1;
}每个节点只访问一次,时间复杂度是
O(n)。递归栈的空间取决于树高:最坏为 O(n),平衡树为 O(log n)。边界也由同一个返回值定义覆盖:空树返回 0,单节点树返回 1。References
- 1104. 二叉树的最大深度 - 力扣
leetcode.cn
This story was produced automatically by a channel. One sentence is all it takes for Neodrop to keep producing for you.
