Skip to content

Commit fa5494b

Browse files
committed
Tree_traversal / 심화
1 parent bd92ea1 commit fa5494b

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// https://www.acmicpc.net/problem/2263
2+
const filePath =
3+
process.platform === "linux"
4+
? "/dev/stdin"
5+
: require("path").join(__dirname, "input.txt")
6+
const input = require("fs").readFileSync(filePath).toString().trim().split("\n")
7+
const log = console.log
8+
9+
// n개의 정점존재, 이진트리의 inorder, postorder 주어지면, preorder 구하기
10+
const n = +input[0]
11+
const inorder = input[1].split(" ").map(Number)
12+
const postorder = input[2].split(" ").map(Number)
13+
let result = ""
14+
15+
// 매번 findIndex하니, 시간초과가 남. => inorder 값의 인덱스를 미리 Map에 저장해두기
16+
const inorderMap = new Map()
17+
inorder.forEach((val, idx) => inorderMap.set(val, idx))
18+
19+
// postorder로 루트 알아내고,
20+
// 그 정보를 통해 inorder에서 왼/오 서브트리 알아내기
21+
// iStart, iEnd: inorder 배열의 범위
22+
// pStart, pEnd: postorder 배열의 범위
23+
const preorder = (iStart, iEnd, pStart, pEnd) => {
24+
if (iStart > iEnd || pStart > pEnd) return
25+
26+
const root = postorder[pEnd]
27+
const rootIdx = inorderMap.get(root)
28+
result += `${root} `
29+
30+
const leftSize = rootIdx - iStart // 왼쪽 서브트리 크기
31+
32+
// 왼쪽 서브트리 처리
33+
preorder(iStart, rootIdx - 1, pStart, pStart + leftSize - 1)
34+
35+
// 오른쪽 서브트리 처리
36+
preorder(rootIdx + 1, iEnd, pStart + leftSize, pEnd - 1)
37+
}
38+
39+
preorder(0, n - 1, 0, n - 1)
40+
log(result.trim())
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
3
2+
1 2 3
3+
1 3 2

0 commit comments

Comments
 (0)