Skip to main content

104. Maximum Depth of Binary Tree

分析

dfs一把梭

题解

type TreeNodeOrNull = TreeNode | null

function maxDepth(root: TreeNodeOrNull): number {
let ans = 0

const dfs = (node: TreeNodeOrNull, depth: number): void => {
if (!node) {
return
}
ans = Math.max(ans, depth)
dfs(node.left, depth + 1)
dfs(node.right, depth + 1)
}

dfs(root, 1)

return ans
};