-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathleetcode0095.go
75 lines (65 loc) · 1.28 KB
/
leetcode0095.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
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
LeetCode 95: https://leetcode.com/problems/unique-binary-search-trees-ii/
*/
package leetcode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func generateTrees(n int) []*TreeNode {
return helper95(1, n)
}
func helper95(low, upper int) []*TreeNode {
if low > upper {
return make([]*TreeNode, 0)
} else if low == upper {
result := make([]*TreeNode, 1)
result[0] = &TreeNode{
Val: low,
}
return result
} else {
result := make([]*TreeNode, 0)
for i := low; i <= upper; i++ {
left := helper95(low, i-1)
right := helper95(i+1, upper)
result = addTrees95(result, left, right, i)
}
return result
}
}
func addTrees95(trees, left, right []*TreeNode, rootVal int) []*TreeNode {
if len(left) == 0 {
for _, r := range right {
root := &TreeNode{
Val: rootVal,
Right: r,
}
trees = append(trees, root)
}
} else if len(right) == 0 {
for _, l := range left {
root := &TreeNode{
Val: rootVal,
Left: l,
}
trees = append(trees, root)
}
} else {
for _, l := range left {
for _, r := range right {
root := &TreeNode{
Val: rootVal,
Left: l,
Right: r,
}
trees = append(trees, root)
}
}
}
return trees
}