File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ package easy ;
2
+
3
+ import classes .TreeNode ;
4
+
5
+ /**112. Path Sum QuestionEditorial Solution My Submissions
6
+ Total Accepted: 115095
7
+ Total Submissions: 360394
8
+ Difficulty: Easy
9
+ Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
10
+
11
+ For example:
12
+ Given the below binary tree and sum = 22,
13
+ 5
14
+ / \
15
+ 4 8
16
+ / / \
17
+ 11 13 4
18
+ / \ \
19
+ 7 2 1
20
+ return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.*/
21
+ public class PathSum {
22
+ public boolean hasPathSum (TreeNode root , int sum ) {
23
+ if (root == null ) return false ;
24
+ if (root .val == sum && root .left == null && root .right == null ) return true ;
25
+ return hasPathSum (root .left , sum - root .val ) || hasPathSum (root .right , sum - root .val );
26
+ }
27
+
28
+ public static void main (String ...strings ){
29
+ PathSum test = new PathSum ();
30
+ // TreeNode root = new TreeNode(1);
31
+ // root.left = new TreeNode(2);
32
+ // int sum = 1;
33
+
34
+ TreeNode root = new TreeNode (1 );
35
+ root .left = new TreeNode (-2 );
36
+ root .left .left = new TreeNode (1 );
37
+ root .left .right = new TreeNode (3 );
38
+ root .right = new TreeNode (-3 );
39
+ root .right .left = new TreeNode (-2 );
40
+ root .left .left .left = new TreeNode (-1 );
41
+ int sum = 2 ;
42
+ // 1
43
+ // / \
44
+ // -2 -3
45
+ // / \ /
46
+ // 1 3 -2
47
+ // /
48
+ // -1
49
+ System .out .println (test .hasPathSum (root , sum ));
50
+ }
51
+ }
You can’t perform that action at this time.
0 commit comments