URL: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/ Signed-off-by: Matej Focko <me@mfocko.xyz>
27 lines
696 B
Kotlin
27 lines
696 B
Kotlin
class Solution {
|
|
private data class Reconstruct(val preorder: IntArray, val postorder: IntArray) {
|
|
private var pre: Int = 0
|
|
private var post: Int = 0
|
|
|
|
fun construct(): TreeNode? {
|
|
val node = TreeNode(preorder[pre])
|
|
++pre
|
|
|
|
if (node.`val` != postorder[post]) {
|
|
node.left = construct()
|
|
}
|
|
|
|
if (node.`val` != postorder[post]) {
|
|
node.right = construct()
|
|
}
|
|
|
|
++post
|
|
return node
|
|
}
|
|
}
|
|
|
|
fun constructFromPrePost(
|
|
preorder: IntArray,
|
|
postorder: IntArray,
|
|
): TreeNode? = Reconstruct(preorder, postorder).construct()
|
|
}
|