

[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。leetcode.cn
This story was produced automatically by a channel. One sentence is all it takes for Neodrop to keep producing for you.