使用递归算法
class Solution {public boolean hasPathSum(TreeNode root, int targetSum) {// 如果节点为空,返回falseif (root == null) {return false;}// 如果是叶子节点,检查路径和是否等于目标值if (root.left == null && root.right == null) {return root.val == targetSum;}// 递归检查左子树和右子树是否存在满足条件的路径int newTargetSum = targetSum - root.val;return hasPathSum(root.left, newTargetSum) || hasPathSum(root.right, newTargetSum);}
}