Skip to content

Commit 83f4e96

Browse files
aQuaaQua
aQua
authored and
aQua
committed
437 wrong answer
1 parent 2c33c61 commit 83f4e96

File tree

2 files changed

+32
-14
lines changed

2 files changed

+32
-14
lines changed

Algorithms/0437.path-sum-iii/path-sum-iii.go

Lines changed: 29 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,36 @@ type TreeNode = kit.TreeNode
88

99
func pathSum(root *TreeNode, sum int) int {
1010
res := 0
11-
if root == nil {
12-
return res
13-
}
11+
path := []int{}
12+
13+
var dfs func(*TreeNode, int, int)
14+
dfs = func(node *TreeNode, level, sum int) {
15+
if node == nil {
16+
return
17+
}
18+
19+
// 根据 level 来更新 path
20+
if level >= len(path) {
21+
path = append(path, node.Val)
22+
} else {
23+
path[level] = node.Val
24+
}
25+
sum -= node.Val
1426

15-
newSum := sum - root.Val
16-
if newSum == 0 {
17-
res++
18-
return 1 + pathSum(root.Left, sum) + pathSum(root.Right, sum)
27+
// 到达 leaf
28+
// 并且,此条路径符合要求
29+
if node.Left == nil && node.Right == nil && sum == 0 {
30+
temp := make([]int, level+1)
31+
// copy 不会复制 path[len(temp):],如果 len(path) > len(temp) 的话
32+
copy(temp, path)
33+
res = append(res, temp)
34+
}
35+
36+
dfs(node.Left, level+1, sum)
37+
dfs(node.Right, level+1, sum)
1938
}
2039

21-
return pathSum(root.Left, sum) +
22-
pathSum(root.Right, sum) +
23-
pathSum(root.Left, newSum) +
24-
pathSum(root.Right, newSum)
40+
dfs(root, 0, sum)
41+
42+
return res
2543
}

Algorithms/0437.path-sum-iii/path-sum-iii_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,10 @@ func Test_Problem0437(t *testing.T) {
2020
}{
2121

2222
{
23-
[]int{8, 5, 3, 5, -2, 2, 1, -3, 11, 0},
24-
[]int{5, 3, -2, 5, 2, 1, 8, -3, 11, 0},
23+
[]int{8, 5, 3, 5, -2, 2, 1, -3, 11, 0, 8},
24+
[]int{5, 3, -2, 5, 2, 1, 8, -3, 11, 0, 8},
25+
8,
2526
8,
26-
6,
2727
},
2828

2929
// 可以多个 testcase

0 commit comments

Comments
 (0)