-
Notifications
You must be signed in to change notification settings - Fork 24
/
leetcode0105.go
41 lines (36 loc) · 1022 Bytes
/
leetcode0105.go
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
LeetCode 105: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
*/
package leetcode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func buildTree(preorder []int, inorder []int) *TreeNode {
return helper105(preorder, inorder, 0, len(preorder)-1, 0, len(inorder)-1)
}
func helper105(preorder, inorder []int, preStart, preEnd, inStart, inEnd int) *TreeNode {
if preStart > preEnd {
return nil
}
root := &TreeNode{Val: preorder[preStart]}
rootInorderIndex := inStart
for ; rootInorderIndex <= inEnd; rootInorderIndex++ {
if inorder[rootInorderIndex] == root.Val {
break
}
}
leftLen := rootInorderIndex - inStart
rightLen := inEnd - inStart - leftLen
root.Left = helper105(preorder, inorder,
preStart+1, preStart+leftLen,
inStart, rootInorderIndex-1)
root.Right = helper105(preorder, inorder,
preEnd-rightLen+1, preEnd,
rootInorderIndex+1, inEnd)
return root
}