File tree Expand file tree Collapse file tree 2 files changed +37
-0
lines changed Expand file tree Collapse file tree 2 files changed +37
-0
lines changed Original file line number Diff line number Diff line change
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.
Original file line number Diff line number Diff line change 23
23
24
24
- [ merge-sorted-array] ( Easy/merge-sorted-array.md )
25
25
26
+ - [ path-sum] ( Easy/path-sum.md )
27
+
26
28
Medium
27
29
------
28
30
You can’t perform that action at this time.
0 commit comments