package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
type TreeNode = structures.TreeNode
func buildTree(preorder []int, inorder []int) *TreeNode {
inPos := make(map[int]int)
for i := 0; i < len(inorder); i++ {
inPos[inorder[i]] = i
}
return buildPreIn2TreeDFS(preorder, 0, len(preorder)-1, 0, inPos)
}
func buildPreIn2TreeDFS(pre []int, preStart int, preEnd int, inStart int, inPos map[int]int) *TreeNode {
if preStart > preEnd {
return nil
}
root := &TreeNode{Val: pre[preStart]}
rootIdx := inPos[pre[preStart]]
leftLen := rootIdx - inStart
root.Left = buildPreIn2TreeDFS(pre, preStart+1, preStart+leftLen, inStart, inPos)
root.Right = buildPreIn2TreeDFS(pre, preStart+leftLen+1, preEnd, rootIdx+1, inPos)
return root
}