본문 바로가기
Beakjoon&프로그래머스/Java

[LeetCode/Java] Maximum Depth of Binary Tree

by 현장 2025. 12. 31.

-Code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {

    public int maxDepth(TreeNode root) {
        return calcMaxDepth(root, 0);
    }

    private static int calcMaxDepth(TreeNode root, int depth) {
        if (root == null) {
            return depth;
        }   
    
        int left = calcMaxDepth(root.left, depth + 1);
        int right = calcMaxDepth(root.right, depth + 1);

        return Math.max(left, right);
    }
}

재귀 문제는 depth를 새 가면서 하는 것이 익숙gㅎ서 매개 변수에 추가를 할 수 없을까 고민하다가 찾아보니 다른 함수를 재 선언해서 만들면 됨을 알게 되었습니다.