Skip to content

Commit dc60485

Browse files
authored
Merge pull request #463 from AlgorithmWithGod/lkhyun
[20250714] BOJ / G1 / 트리의 순회 / 이강현
2 parents 0ada41d + 0a2dd5f commit dc60485

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
```java
2+
import java.util.*;
3+
import java.io.*;
4+
5+
public class Main{
6+
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
7+
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
8+
static StringTokenizer st;
9+
static int N;
10+
static int[] inOrder;
11+
static int[] postOrder;
12+
static int[] findInOrderIdxByValue;
13+
14+
static int[] preOrder;
15+
static int preOrderIdx = 1;
16+
17+
public static void main(String[] args) throws Exception{
18+
N = Integer.parseInt(br.readLine());
19+
inOrder = new int[N+1];
20+
postOrder = new int[N+1];
21+
findInOrderIdxByValue = new int[N+1];
22+
preOrder = new int[N+1];
23+
24+
st = new StringTokenizer(br.readLine());
25+
for (int i = 1; i <= N; i++) {
26+
inOrder[i] = Integer.parseInt(st.nextToken());
27+
findInOrderIdxByValue[inOrder[i]] = i;
28+
}
29+
st = new StringTokenizer(br.readLine());
30+
for (int i = 1; i <= N; i++) {
31+
postOrder[i] = Integer.parseInt(st.nextToken());
32+
}
33+
search(1,N,1,N);
34+
for (int i = 1; i <= N; i++) {
35+
bw.write(preOrder[i]+" ");
36+
}
37+
bw.close();
38+
}
39+
static void search(int InStart, int InEnd, int PostStart, int PostEnd){
40+
if(PostStart > PostEnd) return;
41+
int rootIdx = findInOrderIdxByValue[postOrder[PostEnd]];
42+
preOrder[preOrderIdx++] = postOrder[PostEnd];
43+
int leftSize = rootIdx - InStart;
44+
int rightSize = InEnd - rootIdx;
45+
46+
search(InStart, rootIdx-1,PostStart,PostStart+leftSize-1);
47+
search(rootIdx+1, InEnd, PostEnd-rightSize, PostEnd-1);
48+
}
49+
}
50+
```

0 commit comments

Comments
 (0)