题目

image.png

思路

  • 直接利用先序遍历,再每次遍历的时候减去当前节点的值,终止条件是到叶子节点时,它的值为0;

    代码

    1. public boolean hasPathSum(TreeNode root, int targetSum) {
    2. if (root != null && root.left == null
    3. && root.right == null && targetSum == root.val) return true;
    4. if (root == null || root != null && root.left == null
    5. && root.right == null && targetSum != root.val) return false;
    6. return hasPathSum(root.left, targetSum - root.val)
    7. || hasPathSum(root.right, targetSum - root.val);
    8. }
    路径总和