Leetcode 112.路径总和
题目要求
示例 1:

输入:root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
输出:true
解释:等于目标和的根节点到叶节点路径如上图所示。
示例 2:

输入:root = [1,2,3], targetSum = 5
输出:false
解释:树中存在两条根节点到叶子节点的路径:
(1 --> 2): 和为 3
(1 --> 3): 和为 4
不存在 sum = 5 的根节点到叶子节点的路径。
示例 3:
输入:root = [], targetSum = 0
输出:false
解释:由于树是空的,所以不存在根节点到叶子节点的路径。
前序遍历
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 41 42 43 44
|
class Solution { public boolean hasPathSum(TreeNode root, int targetSum) { if (root == null) return false; return traversal(root, targetSum - root.val); }
public boolean traversal(TreeNode root, int count) { if (root.left == null && root.right == null && count == 0) return true; if (root.left == null && root.right == null) return false; if (root.left != null) { count -= root.left.val; if(traversal(root.left, count)) return true; count += root.left.val; } if (root.right != null) { count -= root.right.val; if(traversal(root.right, count)) return true; count += root.right.val; } return false; } }
|
简洁方法
1 2 3 4 5 6 7 8 9 10 11 12
| 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); } }
|