Skip to content

Commit c6b7428

Browse files
authored
Merge pull request neetcode-gh#1839 from josuebrunel/feat/0112-Path-Sum.go
go: add 0112 Path Sum solution
2 parents cbd1c63 + 4b02f81 commit c6b7428

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

go/0112-Path-Sum.go

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* type TreeNode struct {
4+
* Val int
5+
* Left *TreeNode
6+
* Right *TreeNode
7+
* }
8+
*/
9+
func hasPathSum(root *TreeNode, targetSum int) bool {
10+
if root == nil {
11+
return false
12+
}
13+
14+
return dfs(root, 0, targetSum)
15+
}
16+
17+
func dfs(root *TreeNode, curSum, targetSum int) bool {
18+
if root == nil {
19+
return false
20+
}
21+
curSum += root.Val
22+
if curSum == targetSum && root.Left == nil && root.Right == nil {
23+
return true
24+
}
25+
return dfs(root.Left, curSum, targetSum) || dfs(root.Right, curSum, targetSum)
26+
}

0 commit comments

Comments
 (0)