增加 0112路径和Java 简洁解法

This commit is contained in:
zhenzi
2021-05-15 11:19:14 +08:00
parent 8dedebcc8d
commit b83f378bee

View File

@ -332,6 +332,19 @@ class Solution {
} }
} }
// LC112 简洁方法
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) return false; // 为空退出
// 叶子节点判断是否符合
if (root.left == null && root.right == null) return root.val == targetSum;
// 求两侧分支的路径和
return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
}
}
``` ```
Python Python