kt: add «889. Construct Binary Tree from Preorder and Postorder Traversal»

URL:	https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-02-23 20:51:19 +01:00
parent 2c0920d14e
commit 941a9a13c7
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,27 @@
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()
}