var maxDepth = function(root) {
if (!root) return 0
let depth = 0
let queue = [root]
while (queue.length) {
let size = queue.length
let i = 0
while (i < size) {
let cur = queue[0]
queue.shift()
i++
cur.left && queue.push(cur.left)
cur.right && queue.push(cur.right)
}
depth++
}
return depth
};
遞歸法
var maxDepth = function(root) {
if (!root) return 0
let maxDep = 0
const dfs = (root) => {
if (!root) {
return 0
}
let lDep = dfs(root.left) // 左
let rDep = dfs(root.right) // 右
maxDep = Math.max(lDep, rDep) + 1 // 中
return maxDep
}
return dfs(root)
};