forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0112-path-sum.java
30 lines (29 loc) · 895 Bytes
/
0112-path-sum.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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
//This would be easily solved by DFS and then comparing the values
public boolean dfs(TreeNode root, int targetSum, int currSum){
if(root == null) return false;
currSum += root.val;
if(root.left == null && root.right == null){
return (currSum == targetSum);
}
return dfs(root.left, targetSum, currSum) || dfs(root.right, targetSum, currSum);
}
public boolean hasPathSum(TreeNode root, int targetSum) {
return dfs(root, targetSum, 0);
}
}