File tree 1 file changed +41
-0
lines changed
1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ Author: Annie Kim, [email protected]
3
+ Date: Apr 6, 2013
4
+ Update: Jul 26, 2013
5
+ Problem: Path Sum
6
+ Difficulty: easy
7
+ Source: http://www.leetcode.com/onlinejudge
8
+ Notes:
9
+ Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up
10
+ all the values along the path equals the given sum.
11
+
12
+ For example:
13
+ Given the below binary tree and sum = 22,
14
+ 5
15
+ / \
16
+ 4 8
17
+ / / \
18
+ 11 13 4
19
+ / \ \
20
+ 7 2 1
21
+ return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
22
+
23
+ Solution: Recursion.
24
+ */
25
+ /**
26
+ * Definition for binary tree
27
+ * public class TreeNode {
28
+ * int val;
29
+ * TreeNode left;
30
+ * TreeNode right;
31
+ * TreeNode(int x) { val = x; }
32
+ * }
33
+ */
34
+ public class Solution {
35
+ public boolean hasPathSum (TreeNode root , int sum ) {
36
+ if (root == null ) return false ;
37
+ if (root .left == null && root .right == null ) return sum == root .val ;
38
+ return hasPathSum (root .left , sum - root .val ) ||
39
+ hasPathSum (root .right , sum - root .val );
40
+ }
41
+ }
You can’t perform that action at this time.
0 commit comments