-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path112.go
76 lines (66 loc) · 1.47 KB
/
112.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
package DFS
// 112. Path Sum
// 112. 路径总和
// 思路:DFS 遍历二叉树
// 1、遍历每一个节点,使用 targetSum 减去节点值
// 2、判断 targetSum 是否为0,并且是否达到叶子节点
// time O(n) space O(n)
func hasPathSum(root *TreeNode, targetSum int) bool {
if root == nil {
return false
}
found := false
var dfs func(root *TreeNode, remain int)
dfs = func(root *TreeNode, remain int) {
if root == nil {
return
}
remain -= root.Val
if remain == 0 && root.Left == nil && root.Right == nil {
found = true
return
}
dfs(root.Left, remain)
dfs(root.Right, remain)
}
dfs(root, targetSum)
return found
}
// 思路:回溯型 DFS
// 遍历二叉树,维护一个当前节点和,与targetSum比较即可。
func hasPathSumM(root *TreeNode, targetSum int) bool {
if root == nil {
return false
}
found := false
curSum := 0
var dfs func(root *TreeNode)
dfs = func(root *TreeNode) {
if root == nil {
return
}
// 前序位置
curSum += root.Val
if root.Left == nil && root.Right == nil {
if curSum == targetSum {
found = true
}
}
dfs(root.Left)
dfs(root.Right)
// 后序位置
curSum -= root.Val
}
dfs(root)
return found
}
func hasPathSumN(root *TreeNode, targetSum int) bool {
if root == nil {
return false
}
if root.Left == nil && root.Right == nil {
return targetSum == root.Val
}
targetSum -= root.Val
return hasPathSumN(root.Left, targetSum) || hasPathSumN(root.Right, targetSum)
}