forked from halfrost/LeetCode-Go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path113. Path Sum II.go
71 lines (64 loc) · 1.49 KB
/
113. Path Sum II.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
package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
type TreeNode = structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// 解法一
func pathSum(root *TreeNode, sum int) [][]int {
var slice [][]int
slice = findPath(root, sum, slice, []int(nil))
return slice
}
func findPath(n *TreeNode, sum int, slice [][]int, stack []int) [][]int {
if n == nil {
return slice
}
sum -= n.Val
stack = append(stack, n.Val)
if sum == 0 && n.Left == nil && n.Right == nil {
slice = append(slice, append([]int{}, stack...))
stack = stack[:len(stack)-1]
}
slice = findPath(n.Left, sum, slice, stack)
slice = findPath(n.Right, sum, slice, stack)
return slice
}
// 解法二
func pathSum1(root *TreeNode, sum int) [][]int {
if root == nil {
return [][]int{}
}
if root.Left == nil && root.Right == nil {
if sum == root.Val {
return [][]int{{root.Val}}
}
}
path, res := []int{}, [][]int{}
tmpLeft := pathSum(root.Left, sum-root.Val)
path = append(path, root.Val)
if len(tmpLeft) > 0 {
for i := 0; i < len(tmpLeft); i++ {
tmpLeft[i] = append(path, tmpLeft[i]...)
}
res = append(res, tmpLeft...)
}
path = []int{}
tmpRight := pathSum(root.Right, sum-root.Val)
path = append(path, root.Val)
if len(tmpRight) > 0 {
for i := 0; i < len(tmpRight); i++ {
tmpRight[i] = append(path, tmpRight[i]...)
}
res = append(res, tmpRight...)
}
return res
}