
-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ㅎ서 매개 변수에 추가를 할 수 없을까 고민하다가 찾아보니 다른 함수를 재 선언해서 만들면 됨을 알게 되었습니다.
'Beakjoon&프로그래머스 > Java' 카테고리의 다른 글
| [LeetCode/Java] Search in a Binary Search Tree (0) | 2025.12.31 |
|---|---|
| [LeetCode/Java] Leaf-Similar Trees (0) | 2025.12.31 |
| [LeetCode/Java] Number of Recent Calls (0) | 2025.12.31 |
| [LeetCode/Java] Unique Number of Occurrences (0) | 2025.12.31 |
| [LeetCode/Java] Find the Difference of Two Arrays (0) | 2025.12.31 |