-
Notifications
You must be signed in to change notification settings - Fork 1
/
pathSum.go
80 lines (72 loc) · 1.49 KB
/
pathSum.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
76
77
78
79
80
package pathsum
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func pathSum(root *TreeNode, target int) [][]int {
ans := [][]int{}
path := []int{}
var dfs func(node *TreeNode, target int)
dfs = func(node *TreeNode, target int) {
if node == nil {
return
}
target -= node.Val
path = append(path, node.Val)
defer func() {
path = path[:len(path)-1]
}()
if node.Left == nil && node.Right == nil && target == 0 {
ans = append(ans, append([]int{}, path...))
return
}
dfs(node.Left, target)
dfs(node.Right, target)
}
dfs(root, target)
return ans
}
type pair struct {
node *TreeNode
left int
}
func PathSum(root *TreeNode, target int) [][]int {
if root == nil {
return [][]int{}
}
parent := map[*TreeNode]*TreeNode{}
getPath := func(node *TreeNode) (path []int) {
for ; node != nil; node = parent[node] {
path = append(path, node.Val)
}
for i, j := 0, len(path)-1; i < j; i++ {
path[i], path[j] = path[j], path[i]
j--
}
return
}
ans := [][]int{}
queue := []pair{{root, target}}
for len(queue) > 0 {
p := queue[0]
queue = queue[1:]
node := p.node
left := p.left - node.Val
if node.Left == nil && node.Right == nil {
if left == 0 {
ans = append(ans, getPath(node))
}
} else {
if node.Left != nil {
parent[node.Left] = node
queue = append(queue, pair{node.Left, left})
}
if node.Right != nil {
parent[node.Right] = node
queue = append(queue, pair{node.Right, left})
}
}
}
return ans
}