diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index 1b75113e..ecbefd90 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -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: