Skip to content

Commit 665d0a8

Browse files
author
openset
committed
Add: Path Sum
1 parent d0cedc0 commit 665d0a8

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

problems/path-sum/path_sum.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,24 @@
11
package problem112
2+
3+
import "github.com/openset/leetcode/internal/kit"
4+
5+
// TreeNode - Definition for a binary tree node.
6+
type TreeNode = kit.TreeNode
7+
8+
/**
9+
* Definition for a binary tree node.
10+
* type TreeNode struct {
11+
* Val int
12+
* Left *TreeNode
13+
* Right *TreeNode
14+
* }
15+
*/
16+
func hasPathSum(root *TreeNode, sum int) bool {
17+
if root == nil {
18+
return false
19+
}
20+
if root.Left == nil && root.Right == nil {
21+
return root.Val == sum
22+
}
23+
return hasPathSum(root.Left, sum-root.Val) || hasPathSum(root.Right, sum-root.Val)
24+
}

problems/path-sum/path_sum_test.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,29 @@
11
package problem112
2+
3+
import (
4+
"testing"
5+
6+
"github.com/openset/leetcode/internal/kit"
7+
)
8+
9+
type testType struct {
10+
in []int
11+
sum int
12+
want bool
13+
}
14+
15+
func TestHasPathSum(t *testing.T) {
16+
tests := [...]testType{
17+
{
18+
in: []int{5, 4, 8, 11, kit.NULL, 13, 4, 7, 2, kit.NULL, kit.NULL, kit.NULL, 1},
19+
sum: 22,
20+
want: true,
21+
},
22+
}
23+
for _, tt := range tests {
24+
got := hasPathSum(kit.SliceInt2TreeNode(tt.in), tt.sum)
25+
if got != tt.want {
26+
t.Fatalf("in: %v, got: %v, want: %v", tt.in, got, tt.want)
27+
}
28+
}
29+
}

0 commit comments

Comments
 (0)