forked from srishilesh/Data-Structure-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path112_Path_sum
53 lines (46 loc) · 1.41 KB
/
112_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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// https://leetcode.com/problems/path-sum/
// Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
// BFS APPROACH
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null)
return false;
Queue<TreeNode> queue = new LinkedList();
queue.add(root);
while (!queue.isEmpty()) {
int size = queue.size();
while (size > 0) {
TreeNode node = queue.poll();
if (node.left == null && node.right == null && node.val == sum)
return true;
if (node.left != null) {
node.left.val = node.left.val + node.val;
queue.add(node.left);
}
if (node.right != null) {
node.right.val = node.right.val + node.val;
queue.add(node.right);
}
size --;
}
}
return false;
}
}
// DFS APPROACH
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null) return false;
if(root.left == null && root.right == null) return sum == root.val;
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}
}