Skip to content

Commit e7de609

Browse files
authored
Merge pull request #1814 from AlgorithmWithGod/LiiNi-coder
[20260122] BOJ / G4 / 트리 순회 / 이인희
2 parents e0731da + aced495 commit e7de609

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
```java
2+
import java.io.BufferedReader;
3+
import java.io.IOException;
4+
import java.io.InputStreamReader;
5+
import java.util.ArrayDeque;
6+
import java.util.Arrays;
7+
import java.util.Deque;
8+
import java.util.HashMap;
9+
import java.util.Map;
10+
11+
public class Main {
12+
private static int[] BiTree;
13+
private static Map<Integer, Integer> TreeIdxAtValue;
14+
private static int answer = 0;
15+
private static Deque<Integer> InnerFind;
16+
private static Map<Integer, int[]> ChildsAtParent;
17+
public static void main(String[] args) throws IOException {
18+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
19+
int n = Integer.parseInt(br.readLine());
20+
BiTree = new int[200_010];
21+
InnerFind = new ArrayDeque<>();
22+
TreeIdxAtValue = new HashMap<>();
23+
ChildsAtParent = new HashMap<>();
24+
BiTree[1] = 1;
25+
TreeIdxAtValue.put(1, 1);
26+
int i = n;
27+
while(i-->0) {
28+
String[] temp = br.readLine().split(" ");
29+
int parent = Integer.parseInt(temp[0]);
30+
int a = Integer.parseInt(temp[1]);
31+
int b = Integer.parseInt(temp[2]);
32+
33+
ChildsAtParent.put(parent, new int[] {a, b});
34+
}
35+
dfsTree(1, 1);
36+
// System.out.println(Arrays.toString(BiTree));
37+
//중위순회 마지막 노드 알아내기
38+
findLast(1);
39+
answer--;
40+
dfs(1);
41+
System.out.println(answer);
42+
br.close();
43+
}
44+
45+
private static void dfsTree(int value, int idx){
46+
BiTree[idx] = value;
47+
int[] childValues = ChildsAtParent.get(value);
48+
BiTree[idx*2] = childValues[0];
49+
BiTree[idx*2+1] = childValues[1];
50+
if(childValues[0] != -1)
51+
dfsTree(childValues[0], idx*2);
52+
if(childValues[1] != -1)
53+
dfsTree(childValues[1], idx*2+1);
54+
}
55+
56+
private static void findLast(int cur) {
57+
int a = cur*2;
58+
int b = cur*2+1;
59+
// 왼쪽자식 갈수있으면
60+
if(BiTree[a] != 0 && BiTree[a] != -1){
61+
findLast(a);
62+
}
63+
InnerFind.offerLast(cur);
64+
// 오른쪽자식 갈수있으면
65+
if(BiTree[b] != 0 && BiTree[b] != -1){
66+
findLast(b);
67+
}
68+
}
69+
private static void dfs(int cur) {
70+
answer++;
71+
int a = cur*2;
72+
int b = cur*2+1;
73+
// 왼쪽자식 갈수있으면
74+
if(BiTree[a] != 0 && BiTree[a] != -1){
75+
dfs(a);
76+
answer++;
77+
}
78+
79+
// 오른쪽자식 갈수있으면
80+
if(BiTree[b] != 0 && BiTree[b] != -1){
81+
dfs(b);
82+
answer++;
83+
}
84+
85+
// 유사중위 순회의 끝이라면
86+
if(InnerFind.getLast() == cur){
87+
System.out.println(answer);
88+
System.exit(0);
89+
}
90+
}
91+
}
92+
```

0 commit comments

Comments
 (0)