Skip to content

Commit 36d1f51

Browse files
committed
Add path sum
1 parent 631afb4 commit 36d1f51

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

Easy/path-sum.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
Code
2+
====
3+
4+
```go
5+
/**
6+
* Definition for a binary tree node.
7+
* type TreeNode struct {
8+
* Val int
9+
* Left *TreeNode
10+
* Right *TreeNode
11+
* }
12+
*/
13+
func hasPathSum(root *TreeNode, sum int) bool {
14+
if root == nil {
15+
return false
16+
}
17+
18+
if root.Val-sum == 0 {
19+
if root.Right == nil && root.Left == nil {
20+
return true
21+
}
22+
}
23+
24+
return hasPathSum(root.Right, sum-root.Val) || hasPathSum(root.Left, sum-root.Val)
25+
}
26+
```
27+
28+
Solution in mind
29+
================
30+
31+
- If current node value - sum is equal to 0, AND the node is a leaf node, we have a valid path sum.
32+
33+
- If we ever encounter a nil node, we have reached the end of path and the path is not valid.
34+
35+
- We recursively call to see if either the right sub path or left sub path has a sum equal to sum - current node value.

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ Easy
2323

2424
- [merge-sorted-array](Easy/merge-sorted-array.md)
2525

26+
- [path-sum](Easy/path-sum.md)
27+
2628
Medium
2729
------
2830

0 commit comments

Comments
 (0)