给你二叉树的根节点 root 和一个表示目标和的整数 targetSum ,判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。

    叶子节点 是指没有子节点的节点。

    链接: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. if(!root) return false
    16. let res = false
    17. const depthOrder = (root, sum) => {
    18. if(!root.left && !root.right && sum === targetSum){
    19. res = true
    20. }
    21. if(root.left) depthOrder(root.left, sum+root.left.val)
    22. if(root.right) depthOrder(root.right, sum+root.right.val)
    23. }
    24. depthOrder(root, root.val)
    25. return res
    26. };