baekjoon 20260321
This commit is contained in:
parent
96c620e88e
commit
5baec899f6
40
code_study/Baekjoon/swift/2263.swift
Normal file
40
code_study/Baekjoon/swift/2263.swift
Normal file
@ -0,0 +1,40 @@
|
||||
func main() {
|
||||
guard let n = Int(readLine() ?? "") else { return }
|
||||
guard let line1 = readLine(),
|
||||
let line2 = readLine()
|
||||
else { return }
|
||||
|
||||
let inOrder = line1.split(separator: " ").compactMap{Int($0)}
|
||||
let postOrder = line2.split(separator: " ").compactMap{Int($0)}
|
||||
|
||||
var inOrderIdx = Array(repeating: -1, count: n+1)
|
||||
|
||||
for i in 0..<inOrder.count {
|
||||
inOrderIdx[inOrder[i]] = i
|
||||
}
|
||||
|
||||
var preOrder: [Int] = Array(repeating: 0, count: n)
|
||||
var preIdx = 0
|
||||
|
||||
func order(inOrder_start si: Int, inOrder_end ei: Int, postOrder_start sp: Int, postOrder_end ep: Int) {
|
||||
if(ei < si || ep < sp) {
|
||||
return
|
||||
}
|
||||
|
||||
let root = postOrder[ep]
|
||||
let rootIdx = inOrderIdx[root]
|
||||
|
||||
preOrder[preIdx] = root
|
||||
preIdx += 1
|
||||
|
||||
let leftLength = rootIdx - si
|
||||
|
||||
order(inOrder_start: si, inOrder_end: rootIdx - 1, postOrder_start: sp, postOrder_end: sp + leftLength - 1)
|
||||
order(inOrder_start: rootIdx + 1, inOrder_end: ei, postOrder_start: sp + leftLength, postOrder_end: ep - 1)
|
||||
}
|
||||
|
||||
order(inOrder_start: 0, inOrder_end: n-1, postOrder_start: 0, postOrder_end: n-1)
|
||||
print(preOrder.compactMap({String($0)}).joined(separator: " "))
|
||||
}
|
||||
|
||||
main()
|
||||
Loading…
x
Reference in New Issue
Block a user