Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Example:
- * var ti = TreeNode(5)
- * var v = ti.`val`
- * Definition for a binary tree node.
- * class TreeNode(var `val`: Int) {
- * var left: TreeNode? = null
- * var right: TreeNode? = null
- * }
- */
- class Solution {
- fun bstFromPreorder(preorder: IntArray): TreeNode? {
- if(preorder.size == 0) return null
- val root = TreeNode(preorder[0], null, null)
- buildBst(root, min = Int.MIN_VALUE, max = Int.MAX_VALUE, preorder = preorder, nodeIdx = 1)
- return root
- }
- private fun buildBst(root: TreeNode, min: Int, max: Int, preorder: IntArray, nodeIdx: Int) {
- println("root=${root.`val`}/${root.left}/${root.right}, min=$min, max=$max, node=${preorder[nodeIdx]}")
- if(nodeIdx >= preorder.size) return
- val nodeVal = preorder[nodeIdx]//5
- val node = TreeNode(nodeVal, null, null)
- if(nodeVal > min && nodeVal < root.`val`) {
- root.left = node
- buildBst(root = node, min = min, max = root.`val`, preorder = preorder, nodeIdx = nodeIdx + 1)
- } else if(nodeVal > root.`val` && nodeVal < max) {
- root.right = node
- buildBst(root = node, min = root.`val`, max = max, preorder = preorder, nodeIdx = nodeIdx + 1)
- } else {
- /*error is here. I cannot return to parent boundaries
- input: [8,5,1,7,10,12]
- stdout:
- root=8/null/null, min=-2147483648, max=2147483647, node=5
- root=5/null/null, min=-2147483648, max=8, node=1
- root=1/null/null, min=-2147483648, max=5, node=7
- actual output: [8,5,null,1]
- expected output: [8,5,10,1,7,null,12]
- */
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement