-
Notifications
You must be signed in to change notification settings - Fork 3
/
_0112_PathSum.java
40 lines (34 loc) · 1.18 KB
/
_0112_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
package com.diguage.algorithm.leetcode;
import com.diguage.algorithm.util.TreeNode;
import java.util.Objects;
import static com.diguage.algorithm.util.TreeNodeUtils.*;
import static java.util.Arrays.*;
/**
* = 112. Path Sum
*
* https://leetcode.com/problems/path-sum/[Path Sum - LeetCode]
*
* @author D瓜哥, https://www.diguage.com/
* @since 2020-02-07 21:53
*/
public class _0112_PathSum {
/**
* Runtime: 0 ms, faster than 100.00% of Java online submissions for Path Sum.
* Memory Usage: 39.1 MB, less than 5.88% of Java online submissions for Path Sum.
*/
public boolean hasPathSum(TreeNode root, int sum) {
if (Objects.isNull(root)) {
return false;
}
sum -= root.val;
if ( Objects.isNull(root.left) && Objects.isNull(root.right)) {
return sum == 0;
}
return hasPathSum(root.left, sum) || hasPathSum(root.right, sum);
}
public static void main(String[] args) {
_0112_PathSum solution = new _0112_PathSum();
boolean r1 = solution.hasPathSum(buildTree(asList(5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, null, null, 1)), 22);
System.out.println(r1);
}
}