-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path34.go
87 lines (79 loc) · 1.59 KB
/
34.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
81
82
83
84
85
86
87
package main
/***
"题目:**二叉树中和为某一值的路径**
[二叉树中和为某一值的路径](https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof)
题目描述:
***/
/**
解法一
说明:
**/
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func pathSum(root *TreeNode, sum int) [][]int {
var data [][]int
if root == nil {
return data
}
dfs34(root, sum, []int{}, &data)
return data
}
func dfs34(root *TreeNode, sum int, arr []int, res *[][]int) {
if root == nil {
return
}
arr = append(arr, root.Val)
if root.Val == sum && root.Left == nil && root.Right == nil {
tmp := make([]int, len(arr))
copy(tmp, arr)
*res = append(*res, tmp)
}
dfs34(root.Left, sum-root.Val, arr, res)
dfs34(root.Right, sum-root.Val, arr, res)
arr = arr[:len(arr)-1]
}
/**
解法二
说明:
**/
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func pathSum2(root *TreeNode, sum int) [][]int {
var res [][]int
if root == nil {
return res
}
var path []int
var dfs func(root *TreeNode, sum int)
dfs = func(root *TreeNode, target int) {
if root == nil {
return
}
path = append(path, root.Val)
target -= root.Val
if 0 == target && root.Left == nil && root.Right == nil {
tmp := make([]int, len(path))
copy(tmp, path)
res = append(res, tmp)
}
dfs(root.Left, target)
dfs(root.Right, target)
path = path[0 : len(path)-1]
}
dfs(root, sum)
return res
}
func main() {
}