-
Notifications
You must be signed in to change notification settings - Fork 0
/
Path Sum
37 lines (37 loc) · 1.04 KB
/
Path Sum
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(root == null) return false;
int cal = 0;
if(helpler(root, cal, sum))
return true;
else
return false;
}
private boolean helpler(TreeNode root, int cal, int sum)
{
cal+=root.val;
if(root.left==null && root.right==null)
{
if(cal == sum)
return true;
else
return false;
}
if(root.left != null && root.right != null)
return helpler(root.left, cal, sum) | helpler(root.right, cal, sum);
else if(root.left != null)
return helpler(root.left, cal, sum);
else
return helpler(root.right, cal, sum);
}
}