Skip to content

Commit 860d20d

Browse files
committed
땃쥐 - BOJ_1068 (트리)
1 parent 000cb64 commit 860d20d

File tree

1 file changed

+128
-0
lines changed

1 file changed

+128
-0
lines changed

src/땃쥐/BOJ_1068.java

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
package 땃쥐;
2+
3+
import java.io.IOException;
4+
import java.util.ArrayList;
5+
import java.util.List;
6+
import java.util.Objects;
7+
8+
public class BOJ_1068 {
9+
10+
private static int N; // 노드의 갯수
11+
private static Node[] nodes;
12+
13+
public static void main(String[] args) throws IOException {
14+
N = readInt();
15+
16+
nodes = new Node[N];
17+
18+
for (int i = 0; i < N; i++) {
19+
nodes[i] = new Node(i);
20+
}
21+
22+
for (int i = 0; i < N; i++) {
23+
int parentNodeNumber = readInt();
24+
if (isNotRootNode(parentNodeNumber)) {
25+
nodes[parentNodeNumber].addChild(nodes[i]);
26+
}
27+
}
28+
29+
int deleteNodeNumber = readInt();
30+
nodes[deleteNodeNumber].detach();
31+
32+
int count = 0;
33+
34+
for (Node node : nodes) {
35+
if (node.isLeafNode()) {
36+
count++;
37+
}
38+
}
39+
40+
System.out.print(count);
41+
}
42+
43+
private static boolean isNotRootNode(int parentNodeNumber) {
44+
return parentNodeNumber != -1;
45+
}
46+
47+
private static int readInt() throws IOException {
48+
int value = 0;
49+
boolean negative = false;
50+
51+
int input;
52+
while (true) {
53+
input = System.in.read();
54+
if (input == ' ' || input == '\n') {
55+
return (negative) ? -value : value;
56+
} else if (input == '-') {
57+
negative = true;
58+
} else {
59+
value = value * 10 + (input - 48);
60+
}
61+
}
62+
}
63+
}
64+
65+
class Node {
66+
Node parent;
67+
List<Node> childs = new ArrayList<>();
68+
69+
final int value;
70+
boolean detached;
71+
72+
public Node(int value) {
73+
this.value = value;
74+
}
75+
76+
public int getValue() {
77+
return value;
78+
}
79+
80+
public void addChild(Node child) { // 양방향 참조
81+
childs.add(child);
82+
child.parent = this;
83+
}
84+
85+
public Node getRootNode() {
86+
if (parent == null) {
87+
return this;
88+
}
89+
Node parent = this.parent;
90+
91+
while(true) {
92+
if (parent.parent == null) {
93+
return parent;
94+
}
95+
parent = parent.parent;
96+
}
97+
}
98+
99+
public void detach() {
100+
if (parent != null) {
101+
parent.childs.remove(this);
102+
this.parent = null;
103+
}
104+
detached = true;
105+
}
106+
107+
public boolean isLeafNode() {
108+
return !isRootDetached() && (childs.size() == 0);
109+
}
110+
111+
public boolean isRootDetached() {
112+
return getRootNode().detached;
113+
}
114+
115+
@Override
116+
public boolean equals(Object o) {
117+
if (this == o) return true;
118+
if (o == null || getClass() != o.getClass()) return false;
119+
Node node = (Node) o;
120+
return getValue() == node.getValue();
121+
}
122+
123+
@Override
124+
public int hashCode() {
125+
return Objects.hash(getValue());
126+
}
127+
128+
}

0 commit comments

Comments
 (0)