1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| func buildTree(pr []int, in []int) (head *TreeNode) { var dfs func(pr []int, in []int, l0 int, r0 int, l1 int, r1 int) *TreeNode pos := map[int]int{} for idx, v := range in { pos[v] = idx } dfs = func(pr []int, in []int, l0 int, r0 int, l1 int, r1 int) *TreeNode { if l0 > r0 { return nil }
root := &TreeNode{Val: pr[l0]} idx := pos[pr[l0]] lsize := idx - l1
root.Left = dfs(pr, in, l0+1, lsize+l0, l1, idx-1) root.Right = dfs(pr, in, lsize+l0+1, r0, idx+1, r1) return root }
return dfs(pr, in, 0, len(pr)-1, 0, len(in)-1) }
|