Skip to content

Commit 69b322f

Browse files
committed
백제완: [PG] 150367 표현 가능한 이진트리_241206
1 parent d1cd298 commit 69b322f

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Programmers/Level3/JW_150367.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class JW_150367 {
2+
public int[] solution(long[] numbers) {
3+
int[] answer = new int[numbers.length];
4+
for (int i = 0; i < numbers.length; i++) {
5+
String str = toBinaryString(numbers[i]);
6+
// 표현 가능한 포화 이진 트리일 경우 '1'
7+
answer[i] = chkInOrder(str, 0, str.length() - 1) ? 1 : 0;
8+
}
9+
return answer;
10+
}
11+
12+
// 포화 이진 트리 -> 문자열 길이가 2^n - 1 꼴이 되어야 함
13+
private String toBinaryString(long number) {
14+
StringBuilder sb = new StringBuilder(Long.toBinaryString(number));
15+
int n = 1;
16+
while (sb.length() > (1 << n) - 1) {
17+
n++;
18+
}
19+
// 빈 부분 채우기
20+
sb.insert(0, "0".repeat((1 << n) - 1 - sb.length()));
21+
return sb.toString();
22+
}
23+
24+
// 중위 탐색을 진행하면서 불가능한 트리인지 확인
25+
private boolean chkInOrder(String str, int l, int r) {
26+
// 리프노드 일 경우는 True
27+
if (l == r)
28+
return true;
29+
int rootIdx = (l + r) / 2;
30+
// 루트 노드가 0'일 경우에는 자식에 '1'이 있으면 안됨
31+
if (str.charAt(rootIdx) == '0')
32+
for (int i = l; i <= r; i++)
33+
if (str.charAt(i) == '1')
34+
return false;
35+
// 다음 중위 탐색
36+
return chkInOrder(str, l, rootIdx - 1) && chkInOrder(str, rootIdx + 1, r);
37+
}
38+
}

0 commit comments

Comments
 (0)