-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
62 lines (47 loc) · 772 Bytes
/
main.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package main
func main() {
}
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func constructMaximumBinaryTree(nums []int) *TreeNode {
root := &TreeNode{}
dfs(root, nums)
return root
}
func dfs(root *TreeNode, nums []int) {
if root == nil || len(nums) == 0 {
return
}
max, ind := maxArr(nums)
if ind == -1 {
return
}
root.Val = max
root.Left = crt(nums[:ind])
root.Right = crt(nums[ind+1:])
dfs(root.Left, nums[:ind])
dfs(root.Right, nums[ind+1:])
}
func crt(nums []int) *TreeNode {
max, ind := maxArr(nums)
if ind == -1 {
return nil
}
return &TreeNode{
Val: max,
}
}
func maxArr(arr []int) (max int, ind int) {
ind = -1
max = -1
for i, v := range arr {
if v > max {
max = v
ind = i
}
}
return
}