-
Notifications
You must be signed in to change notification settings - Fork 19
/
PathSum.java
36 lines (33 loc) · 872 Bytes
/
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
boolean hasPath = false;
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
traverse(root, 0, sum);
return hasPath;
}
public void traverse(TreeNode root, int val, int sum) {
if (root.left == null && root.right == null) {
if (root.val + val == sum) {
hasPath = true;
}
return;
}
if (root.left != null) {
traverse(root.left, val + root.val, sum);
}
if (root.right != null) {
traverse(root.right, val + root.val, sum);
}
}
}