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:
parent
2c0920d14e
commit
941a9a13c7
1 changed files with 27 additions and 0 deletions
|
@ -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()
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue