Skip to content

Commit 4a9fc9b

Browse files
committed
배수빈: [BOJ] 150367 표현 가능한 이진트리_241206
1 parent e90ff09 commit 4a9fc9b

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Programmers/Level3/SB_150367.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class SB_150367 {
2+
private static boolean dfs(String sub) {
3+
int root = sub.length() / 2;
4+
5+
if (sub.length() ==1) return true;
6+
7+
// 부모가 없는데 자식이 존재하면 이진트리 구성 못함
8+
if (sub.charAt(root)=='0' && (sub.substring(0, root).contains("1") || sub.substring(root+1).contains("1"))) return false;
9+
10+
// 양쪽 모두 모순이 없을 경우 true
11+
return dfs(sub.substring(0, root)) && dfs(sub.substring(root + 1));
12+
}
13+
14+
private static String num2bin(long num) {
15+
StringBuilder bin = new StringBuilder(Long.toBinaryString(num));
16+
long len = bin.length();
17+
int n = 0;
18+
while ((1L << n) - 1 < len) { // 2^n-1로 자리를 맞추기 위한 n찾기
19+
n++;
20+
}
21+
22+
while (bin.length() < (1 << n) - 1) { // 2^n-1로 길이 맞추기
23+
bin.insert(0, "0");
24+
}
25+
26+
return bin.toString();
27+
}
28+
public static int[] solution(long[] numbers) {
29+
int N = numbers.length;
30+
int[] ans = new int[N];
31+
32+
for (int i = 0; i < N; i++) {
33+
// 이진수로 만들기
34+
String bin = num2bin(numbers[i]);
35+
36+
// 부모 자식 연결 확인
37+
ans[i] = dfs(bin) ? 1 : 0;
38+
}
39+
40+
return ans;
41+
}
42+
}

0 commit comments

Comments
 (0)