小于 1 分钟
function maxDeep (root){
if(root === null) return 0
// 把左右节点作为子问题来处理
const leftMax = maxDeep(root.left)
const rightMax = maxDeep(root.right)
// 当前节点的 + 左右节点深度的最大值
return 1 + Math.max(leftMax, rightMax)
}
直接遍历
function maxDeep (root) {
let result = 0
function travel(root, deep){
if(root === null) return
// 节点不为空,让深度加一
deep++
// 更新最大深度
result = Math.max(result, deep)
travel(root.left, deep)
travel(root.right, deep)
}
travel(root, 0)
return result
}