import java.io.BufferedWriter
fun main() {
val bufferedReader = System.`in`.bufferedReader()
val bufferedWriter = System.out.bufferedWriter()
val preOrder = mutableListOf<Int>()
while (true) {
val node = bufferedReader.readLine() ?: break
preOrder.add(node.toInt())
}
getPostOrder(preOrder, 0, preOrder.size - 1, bufferedWriter)
bufferedReader.close()
bufferedWriter.close()
}
fun getPostOrder(preOrder: List<Int>, left: Int, right: Int, bufferedWriter: BufferedWriter) {
if (left > right) return
val root = preOrder[left]
var rightChildIndex = -1
for (i in (left + 1)..right) {
if (root < preOrder[i]) {
rightChildIndex = i
break
}
}
if (rightChildIndex == -1) {
rightChildIndex = right + 1
}
getPostOrder(preOrder, left + 1, rightChildIndex - 1, bufferedWriter)
getPostOrder(preOrder, rightChildIndex, right, bufferedWriter)
bufferedWriter.write("$root\n")
}
reference