首发于 语雀@blueju

    https://leetcode-cn.com/problems/path-sum/

    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. function traverse(root) {
    16. if (root === null) {
    17. return
    18. }
    19. trace.push(root.val)
    20. if (root.left === null && root.right === null) {
    21. let total = trace.reduce((prev, curr) => prev + curr, 0)
    22. if (total === targetSum) {
    23. found = true
    24. }
    25. trace.pop()
    26. return
    27. }
    28. traverse(root.left)
    29. traverse(root.right)
    30. trace.pop()
    31. }
    32. let found = false
    33. let trace = []
    34. traverse(root)
    35. return found
    36. };