-
Notifications
You must be signed in to change notification settings - Fork 5
/
PathSum.java
35 lines (30 loc) · 1.07 KB
/
PathSum.java
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
/*
Problem Statement:
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.
Note: A leaf is a node with no children.
Problem Link:
Path Sum:https://leetcode.com/problems/path-sum/description/
Solution:
https://github.com/sunnypatel165/leetcode-again/blob/master/solutions/DetectCapital.java
Author:
Sunny Patel
https://github.com/sunnypatel165
https://www.linkedin.com/in/sunnypatel165/
*/
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
return hasPathSumHelper(root, 0, sum);
}
public boolean hasPathSumHelper(TreeNode root, int current, int sum){
if(root==null)
return false;
if( root.left == null && root.right==null){
if(current + root.val ==sum){
return true;
}
return false;
}
return hasPathSumHelper(root.left, current+root.val, sum) || hasPathSumHelper(root.right, current+root.val, sum);
}
}