Skip to content

Instantly share code, notes, and snippets.

@snowmerak
Created November 22, 2020 11:05
Show Gist options
  • Save snowmerak/b983ad0f7bada592c7cfd49f916f4700 to your computer and use it in GitHub Desktop.
Save snowmerak/b983ad0f7bada592c7cfd49f916f4700 to your computer and use it in GitHub Desktop.
get post order of binary tree from it's pre order and inner order
fun main() {
testGetPostOrder()
}
fun testGetPostOrder() {
val testSet = arrayOf(
Triple(arrayOf(7, 5, 1, 6, 2, 9, 4, 3, 8), arrayOf(1, 5, 2, 6, 9, 7, 3, 4, 8), arrayOf(1, 2, 9, 6, 5, 3, 8, 4, 7)),
Triple(arrayOf(1, 2, 3), arrayOf(2, 1, 3), arrayOf(2, 3, 1)),
Triple(arrayOf(2, 3, 1), arrayOf(1, 2, 3), null),
Triple(arrayOf(9, 6, 7, 2, 3, 4, 5, 8), arrayOf(7, 6, 3, 2, 4, 9, 8, 5), arrayOf(7, 3, 4, 2, 6, 8, 5, 9))
)
testSet.forEach {
println("-case-")
println("expected: ${it.third?.joinToString(separator = ", ")}")
val result = getPostOrder(it.first, it.second)
println("actually: ${result?.joinToString(separator = ", ")}")
println("ok? ${it.third.contentEquals(result)}")
println()
}
}
fun getPostOrder(preOrder: Array<Int>, innerOrder: Array<Int>): Array<Int>? {
var result = Array<Int>(0) {0}
val headPos = innerOrder.indexOf(preOrder[0])
val rightStart = headPos+1;
val end = preOrder.size;
for (i in 0 until headPos) {
for (j in i+1 until end) {
if (preOrder[j] == innerOrder[i]) {
result = result.plus(innerOrder[i])
}
}
}
for (i in headPos-1 downTo 0) {
if (preOrder[i] == innerOrder[i]) {
result = result.plus(innerOrder[i])
}
}
for (i in 0 until headPos) {
for (j in i-1 downTo 1) {
if (preOrder[j] == innerOrder[i]) {
result = result.plus(innerOrder[i])
}
}
}
for (i in rightStart until end) {
for (j in i+1 until end) {
if (preOrder[j] == innerOrder[i]) {
result = result.plus(innerOrder[i])
}
}
}
for (i in headPos until end) {
if (preOrder[i] == innerOrder[i]) {
result = result.plus(innerOrder[i])
}
}
for (i in rightStart until end) {
for (j in i-1 downTo headPos+1) {
if (preOrder[j] == innerOrder[i]) {
result = result.plus(innerOrder[i])
}
}
}
result = result.plus(preOrder[0])
if (result.size == end) {
return result
}
return null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment