35 lines
688 B
Go
35 lines
688 B
Go
package q105
|
|
|
|
type TreeNode struct {
|
|
Val int
|
|
Left *TreeNode
|
|
Right *TreeNode
|
|
}
|
|
|
|
func bld(preorder []int, inorder map[int]int, pL, pR, iL, iR int) *TreeNode {
|
|
if pL == pR {
|
|
return nil
|
|
}
|
|
|
|
val := preorder[pL]
|
|
p := inorder[val] // position of val in "inorder"
|
|
|
|
left := bld(preorder, inorder, pL+1, pL+1+p-iL, iL, p)
|
|
right := bld(preorder, inorder, pL+1+p-iL, pR, p+1, iR)
|
|
|
|
return &TreeNode{
|
|
Val: val,
|
|
Left: left,
|
|
Right: right,
|
|
}
|
|
}
|
|
|
|
func buildTree(preorder []int, inorder []int) *TreeNode {
|
|
iIdx := make(map[int]int, len(inorder))
|
|
for i := range inorder {
|
|
iIdx[inorder[i]] = i
|
|
}
|
|
return bld(preorder, iIdx, 0, len(preorder), 0, len(preorder))
|
|
}
|
|
|
|
var _ = buildTree
|