题目

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

解题

  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 {number[][]}
  13. */
  14. var pathSum = function(root, targetSum) {
  15. if (root === null) {
  16. return []
  17. }
  18. const result = []
  19. const path = []
  20. const dfs = (root, targetSum) => {
  21. if (root === null) return
  22. path.push(root.val)
  23. targetSum -= root.val
  24. if (!root.left && !root.right && targetSum === 0) { // 叶子节点
  25. result.push([...path])
  26. }
  27. dfs(root.left, targetSum)
  28. dfs(root.right, targetSum)
  29. path.pop()
  30. }
  31. dfs(root, targetSum)
  32. return result
  33. };