-
Notifications
You must be signed in to change notification settings - Fork 1
/
PathSum.java
64 lines (50 loc) · 1.77 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.leetcode;
public class PathSum {
//https://leetcode.com/problems/path-sum/
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 {
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null) return false;
return hasPathSumHelper(root,sum,0);
}
public boolean hasPathSumHelper(TreeNode node, int target , int sum){
sum = sum + node.val;
if(node.left == null && node.right == null){
if(sum == target) return true;
else return false;
}
boolean leftHasSum = false;
if(node.left != null){
leftHasSum = hasPathSumHelper(node.left, target , sum);
}
boolean rightHasSum = false;
if(node.right != null){
rightHasSum = hasPathSumHelper(node.right, target , sum);
}
return rightHasSum || leftHasSum;
}
}
}
// Alternate
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root == null) return false;
return hasPathSumHelper(root,targetSum);
}
public boolean hasPathSumHelper(TreeNode node, int target){
if(node == null) return false;
if(node.left == null && node.right == null && node.val == target) return true;
int val = node.val;
int sum = target - val;
return hasPathSumHelper(node.left , sum) || hasPathSumHelper(node.right , sum);
}