2263번: 트리의 순회
첫째 줄에 n(1≤n≤100,000)이 주어진다. 다음 줄에는 인오더를 나타내는 n개의 자연수가 주어지고, 그 다음 줄에는 같은 식으로 포스트오더가 주어진다.
www.acmicpc.net
풀이 )
전위, 중위, 후위 순회 시 구조를 보고 풀었다.
- 전위: root ( left ) ( right )
- 중위: ( left ) root ( right )
- 후위: ( left ) ( right ) root
후위 순회 결과의 마지막이 root이고 이를 이용해서 중위 순회에서의 root 위치를 찾아 좌 우를 나눈다.
중위 순회에서의 root 위치를 빠르게 찾기 위해 index를 저장하는 배열을 만들었다.
import java.io.*;
public class Main {
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
static int[] inOrder;
static int[] postOrder;
static int[] index;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
String[] in;
int n = Integer.parseInt(br.readLine());
inOrder = new int[n+1];
postOrder = new int[n+1];
index = new int[n+1];
in = br.readLine().split(" ");
for(int i = 0; i < n; ++i){
inOrder[i] = Integer.parseInt(in[i]);
index[inOrder[i]] = i;
}
in = br.readLine().split(" ");
for(int i = 0; i < n; ++i)
postOrder[i] = Integer.parseInt(in[i]);
preOrder(0, n-1, 0, n-1);
bw.flush();
}
static void preOrder(int inSrt, int inEnd, int postSrt, int postEnd) throws IOException {
if(inSrt > inEnd || postSrt > postEnd)
return;
int root = postOrder[postEnd];
bw.write(root+" ");
int idx = index[root];
preOrder(inSrt, idx-1, postSrt, postSrt+(idx-1-inSrt));
preOrder(idx+1, inEnd, postSrt+(idx-inSrt), postEnd-1);
}
}
주의 )
인덱스 실수
'문제풀이 > 백준' 카테고리의 다른 글
[JAVA] 백준 - 16947 : 서울 지하철 2호선 (0) | 2021.08.31 |
---|---|
[JAVA] 백준 - 17612 : 쇼핑몰 (0) | 2021.04.02 |
[JAVA] 백준 - 10819 : 차이를 최대로 (0) | 2021.02.27 |
[JAVA] 백준 - 17142 : 연구소 3 (0) | 2021.02.26 |
[JAVA] 백준 - 16235 : 나무 재테크 (0) | 2021.02.23 |