-
Notifications
You must be signed in to change notification settings - Fork 15
/
p275.java
67 lines (48 loc) · 1.47 KB
/
p275.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.util.Scanner;
class N {
char val;
N right, left;
N(char x) {
val = x;
}
}
public class p275 {
static void leerArbol(N node) {
if (index == input.length()) return;
if (input.charAt(index) == 'R') {
node.left = new N(input.charAt(index));
index++;
leerArbol(node.left);
}
index++;
if (input.charAt(index) == 'R') {
node.right = new N(input.charAt(index));
index++;
leerArbol(node.right);
}
}
static int getDeep(N node, int altura) {
if (node == null) return altura;
return Math.max(getDeep(node.left, altura + 1), getDeep(node.right, altura + 1));
}
static boolean estaEquilibrado(N node) {
if (node == null) return true;
int left = getDeep(node.left, 0);
int right = getDeep(node.right, 0);
boolean correct = estaEquilibrado(node.left) && estaEquilibrado(node.right);
if (Math.abs(left - right) > 1) return false;
return correct;
}
static int index;
static String input;
public static void main(String[] args) {
final Scanner s = new Scanner(System.in);
for (int i = s.nextInt(); i > 0; i--) {
input = s.next();
index = 0;
N tree = new N(input.charAt(index++));
leerArbol(tree);
System.out.println( (estaEquilibrado(tree)) ? "SI" : "NO" );
}
}
}