Skip to content

Commit 711bfe4

Browse files
committed
finish "112. Path Sum". Fix #112
1 parent 18f1cc4 commit 711bfe4

File tree

3 files changed

+59
-6
lines changed

3 files changed

+59
-6
lines changed

README.adoc

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -676,12 +676,12 @@
676676
|{doc_base_url}/0111-minimum-depth-of-binary-tree.adoc[Note]
677677
|Easy
678678

679-
//|112
680-
//|{leetcode_base_url}/path-sum/[Path Sum]
681-
//|{source_base_url}/_0112_PathSum.java[Java]
682-
//|{doc_base_url}/0112-path-sum.adoc[Note]
683-
//|Easy
684-
//
679+
|112
680+
|{leetcode_base_url}/path-sum/[Path Sum]
681+
|{source_base_url}/_0112_PathSum.java[Java]
682+
|{doc_base_url}/0112-path-sum.adoc[Note]
683+
|Easy
684+
685685
//|113
686686
//|{leetcode_base_url}/path-sum-ii/[Path Sum II]
687687
//|{source_base_url}/_0113_PathSumII.java[Java]

docs/0112-path-sum.adoc

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,6 @@ Given the below binary tree and `sum = 22`,
2323

2424
return true, as there exist a root-to-leaf path `5->4->11->2` which sum is 22.
2525

26+
=== 解题分析
27+
28+
减去当前节点值的只,然后递归调用,到叶子节点和目标值相等即可。
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package com.diguage.algorithm.leetcode;
2+
3+
import com.diguage.algorithm.util.TreeNode;
4+
5+
import java.util.Objects;
6+
7+
import static com.diguage.algorithm.util.TreeNodeUtils.*;
8+
import static java.util.Arrays.*;
9+
10+
/**
11+
* = 112. Path Sum
12+
*
13+
* https://leetcode.com/problems/path-sum/[Path Sum - LeetCode]
14+
*
15+
* @author D瓜哥, https://www.diguage.com/
16+
* @since 2020-02-07 21:53
17+
*/
18+
public class _0112_PathSum {
19+
20+
/**
21+
* Runtime: 0 ms, faster than 100.00% of Java online submissions for Path Sum.
22+
* Memory Usage: 39.1 MB, less than 5.88% of Java online submissions for Path Sum.
23+
*/
24+
public boolean hasPathSum(TreeNode root, int sum) {
25+
if (Objects.isNull(root)) {
26+
return false;
27+
}
28+
if (Objects.nonNull(root) && root.val == sum
29+
&& Objects.isNull(root.left) && Objects.isNull(root.right)) {
30+
return true;
31+
}
32+
boolean result = false;
33+
if (Objects.nonNull(root.left)) {
34+
result = hasPathSum(root.left, sum - root.val);
35+
}
36+
if (result) {
37+
return true;
38+
}
39+
if (Objects.nonNull(root.right)) {
40+
result = hasPathSum(root.right, sum - root.val);
41+
}
42+
return result;
43+
}
44+
45+
public static void main(String[] args) {
46+
_0112_PathSum solution = new _0112_PathSum();
47+
boolean r1 = solution.hasPathSum(buildTree(asList(5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, null, null, 1)), 22);
48+
System.out.println(r1);
49+
}
50+
}

0 commit comments

Comments
 (0)