leetcode

题目

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

思路

深度优先遍历
从root遍历到叶子节点,看叶子节点的val是否等于剩余的targetSum

解法

  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 === null) {
  16. return false
  17. }
  18. if (!root.left && !root.right) {
  19. return targetSum === root.val
  20. }
  21. return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val)
  22. };