Skip to content

Commit 549550f

Browse files
committed
refactor code #112
1 parent 711bfe4 commit 549550f

File tree

2 files changed

+6
-14
lines changed

2 files changed

+6
-14
lines changed

docs/0112-path-sum.adoc

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,5 @@ return true, as there exist a root-to-leaf path `5->4->11->2` which sum is 22.
2626
=== 解题分析
2727

2828
减去当前节点值的只,然后递归调用,到叶子节点和目标值相等即可。
29+
30+
注意把代码写简化点!

src/main/java/com/diguage/algorithm/leetcode/_0112_PathSum.java

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -25,21 +25,11 @@ public boolean hasPathSum(TreeNode root, int sum) {
2525
if (Objects.isNull(root)) {
2626
return false;
2727
}
28-
if (Objects.nonNull(root) && root.val == sum
29-
&& Objects.isNull(root.left) && Objects.isNull(root.right)) {
30-
return true;
28+
sum -= root.val;
29+
if ( Objects.isNull(root.left) && Objects.isNull(root.right)) {
30+
return sum == 0;
3131
}
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;
32+
return hasPathSum(root.left, sum) || hasPathSum(root.right, sum);
4333
}
4434

4535
public static void main(String[] args) {

0 commit comments

Comments
 (0)