递归方式,代码最简洁。
答案:
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) { // 为空
return false; // 返回false
}
if (root.left == null && root.right == null) { // 如果左右子树都为空
// 判断根节点的值和目标值是否相等,相等则为true,不相等就是false。
return targetSum == root.val;
}
// 继续搜索左子树和右子树
return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
}
}