Goal
Solution
import java.io.BufferedReader
import java.io.BufferedWriter
fun main() {
val bufferedReader = System.`in`.bufferedReader()
val bufferedWriter = System.out.bufferedWriter()
val n = bufferedReader.readLine().toInt()
val inOrder = getOrder(bufferedReader)
val postOrder = getOrder(bufferedReader)
printPreOrder(bufferedWriter, inOrder, postOrder, 0, n - 1, 0, n - 1)
bufferedReader.close()
bufferedWriter.close()
}
fun getRootIndexFromInOrder(inOrder: List<Int>, root: Int): Int {
for (i in inOrder.indices) {
if (inOrder[i] == root) return i
}
return -1
}
fun printPreOrder(
bufferedWriter: BufferedWriter,
inOrder: List<Int>,
postOrder: List<Int>,
inStart: Int,
inEnd: Int,
postStart: Int,
postEnd: Int
) {
if (inStart > inEnd || postStart > postEnd) return
val rootIndexFromInOrder = getRootIndexFromInOrder(inOrder, postOrder[postEnd])
bufferedWriter.write("${inOrder[rootIndexFromInOrder]} ")
val numberOfLeftNode = rootIndexFromInOrder - inStart
printPreOrder(
bufferedWriter,
inOrder,
postOrder,
inStart,
rootIndexFromInOrder - 1,
postStart,
postStart + numberOfLeftNode - 1
)
printPreOrder(
bufferedWriter,
inOrder,
postOrder,
rootIndexFromInOrder + 1,
inEnd,
postStart + numberOfLeftNode,
postEnd - 1
)
}
fun getOrder(bufferedReader: BufferedReader): List<Int> {
return bufferedReader
.readLine()
.split(" ")
.map { it.toInt() }
}
import java.io.BufferedReader
import java.io.BufferedWriter
private lateinit var bufferedReader: BufferedReader
private lateinit var bufferedWriter: BufferedWriter
private lateinit var inOrder: List<Int>
private lateinit var postOrder: List<Int>
private lateinit var inOrderMap: MutableMap<Int, Int>
fun main() {
bufferedReader = System.`in`.bufferedReader()
bufferedWriter = System.out.bufferedWriter()
val n = bufferedReader.readLine().toInt()
inOrder = getOrder()
postOrder = getOrder()
inOrderMap = mutableMapOf()
inOrder.forEachIndexed { index, node ->
inOrderMap[node] = index
}
printPreOrder(0, n - 1, 0, n - 1)
bufferedReader.close()
bufferedWriter.close()
}
fun printPreOrder(inStart: Int, inEnd: Int, postStart: Int, postEnd: Int) {
if (inStart > inEnd || postStart > postEnd) return
val rootIndexFromInOrder = inOrderMap[postOrder[postEnd]]!!
bufferedWriter.write("${inOrder[rootIndexFromInOrder]} ")
val numberOfLeftNode = rootIndexFromInOrder - inStart
printPreOrder(inStart, rootIndexFromInOrder - 1, postStart, postStart + numberOfLeftNode - 1)
printPreOrder(rootIndexFromInOrder + 1, inEnd, postStart + numberOfLeftNode, postEnd - 1)
}
fun getOrder(): List<Int> {
return bufferedReader
.readLine()
.split(" ")
.map { it.toInt() }
}