📚 단일 패턴
104. Maximum Depth of Binary Tree
재귀 DFS 로 이진 트리의 루트에서 가장 깊은 리프까지의 최대 깊이를 계산하는 방법 정리
Oct 5, 2025 — tree
- LeetCode 104. Maximum Depth of Binary Tree (opens in a new window)
- tree 의 최대 깊이를 구하는 문제.
- tree 의 dfs 순회 시에는 전위/중위/후위 순회 중에서 무엇을 써야하는지 고민해야 함.
- 전위는 top-down
- 후위는 bottom-up 으로 bottom 까지 내려간 후 재귀가 풀리면서 계산됨.
- 이 문제는 bottom 의 null node 에서는 depth 0 반환하고, 그 위에 +1 반환하면 bottom-up 계산 가능함.
- 한 node 에서는 depth 계산 방법
- child 의 left, right 의 depth 를 구하면 이번 node 의 dpeth 는 Math.max(left, right) + 1 이 됨.
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } *//** * @param {TreeNode} root * @return {number} */var maxDepth = function(root) { const dfs = (node) => { if (!node) return 0;
const left = dfs(node.left); const right = dfs(node.right);
return Math.max(left, right) + 1; }
return dfs(root);};