Skip to content

Commit 88fe208

Browse files
committed
create path-sum.java
1 parent d79e8f5 commit 88fe208

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Java/path-sum.java

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
14+
* }
15+
*/
16+
class Solution {
17+
public boolean hasPathSum(TreeNode root, int sum) {
18+
if(root == null){
19+
// exception
20+
return false;
21+
}
22+
if(root.left == null && root.right == null){
23+
if(sum == root.val){
24+
return true;
25+
}
26+
return false;
27+
}
28+
else{
29+
boolean left = false;
30+
boolean right = false;
31+
if(root.left != null){
32+
left = hasPathSum(root.left, sum-root.val);
33+
}
34+
if(root.right != null){
35+
right = hasPathSum(root.right, sum-root.val);
36+
}
37+
return left||right;
38+
}
39+
}
40+
}

0 commit comments

Comments
 (0)