
난이도: ★★☆☆☆ • solved on: 2025-12-05

자료구조
알고리즘/기법
핵심 키워드
- 문제 분해
- height 증가 시점을 명확하게 잡기 어렵다고 판단하여,
“child가 있으면 +1, 없으면 0으로 전환”하는 방식을 채택했다.- 기본값을 1로 두고, 자식이 없는 경우 height를 0으로 조정한다.
- 핵심 로직 흐름
if root == null → 0 tmpLeft = 1, tmpRight = 1 왼쪽 자식이 있으면 height(left) 더하기 없으면 tmpLeft = 0 오른쪽 동일 처리 return max(tmpLeft, tmpRight)
예외 처리
- 자식이 없는 leaf 노드는 height = 0
- null root height = 0
public static int height(Node root) {
if (root == null) {
return 0;
}
int tmpLeft = 1;
int tmpRight = 1;
int tmpRoot = 0;
if (root.left != null) {
tmpLeft += height(root.left);
} else {
tmpLeft = 0;
}
if (root.right != null) {
tmpRight += height(root.right);
} else {
tmpRight = 0;
}
return tmpRoot + Math.max(tmpLeft, tmpRight);
}
- 문제 분해
- 트리 height = “두 서브트리의 height 중 큰 값 + 1”
- leaf 노드의 height는 0
- null 노드는 height = 0 으로 처리하면 HackerRank 기준과 일치한다.
- 핵심 로직 흐름
if root is null: return 0 left = height(root.left) right = height(root.right) return max(left, right) + 1
예외 처리
- root가 null → height = 0
- leaf 노드는 left=right=0 → height = 1?
HackerRank에서는 leaf height = 0이므로 위 수식을 기반으로 0을 유지한다.
public static int height(Node root) {
if (root == null) {
return 0;
}
int left = height(root.left);
int right = height(root.right);
return Math.max(left, right) + 1;
}
두 방식 모두 DFS 기반이므로 동일한 복잡도를 가진다. 하지만 가독성 면에서 방법 2가 압도적으로 좋다
비슷한 유형 (GPT 추천)
확장 문제 (GPT 추천)