CodingTest/LeetCode

[LeetCode] 104. Maximum Depth of Binary Tree, Easy

뜸부깅 2025. 4. 7. 15:10
반응형

1. 문제

  • 이진트리가 주어질 때, 최대 깊이를 반환하라.

2. 해결

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function maxDepth(root: TreeNode | null): number {
    if(!root) return 0;
    
    let left_depth = maxDepth(root.left);
    let right_depth = maxDepth(root.right);
    
    return Math.max(left_depth, right_depth) + 1
};
  • 이진 트리 문제를 해결하는 방법에는 Top-Down, Bottom-Up 2가지 방법으로 풀 수 있다.
  • 해당 함수는 추가 파라미터를 받지 않기 때문에 Bottom-Up 방법으로 해결했다.
  • 리프 노드를 찾을 때 까지 탐색 후, 깊이 값을 root로 돌아오며 누적하는 방식.