1. /**
    2. * Definition for a binary tree node.
    3. * function TreeNode(val, left, right) {
    4. * this.val = (val===undefined ? 0 : val)
    5. * this.left = (left===undefined ? null : left)
    6. * this.right = (right===undefined ? null : right)
    7. * }
    8. */
    9. /**
    10. * @param {TreeNode} root
    11. * @param {number} targetSum
    12. * @return {boolean}
    13. */
    14. var hasPathSum = function(root, targetSum) {
    15. let result = false
    16. let dfs = (data, presum, tar) => {
    17. if (data) {
    18. presum = data.val + presum
    19. if (!data.left && !data.right) {
    20. if (presum == tar) {
    21. result = true
    22. }
    23. }
    24. dfs(data.left, presum, tar)
    25. dfs(data.right, presum, tar)
    26. }
    27. }
    28. dfs(root, 0, targetSum)
    29. return result
    30. };

    image.png