给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。

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

    示例 1:

    image.png
    输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
    输出:[[5,4,11,2],[5,8,4,5]]
    示例 2:

    输入:root = [1,2,3], targetSum = 5
    输出:[]
    示例 3:

    输入:root = [1,2], targetSum = 0
    输出:[]

    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. // 递归法
    16. // 要遍历整个树找到所有路径,所以递归函数不需要返回值, 与112不同
    17. const res = [];
    18. const traverse = (node, cnt, path) => {
    19. // 遇到了叶子节点且找到了和为sum的路径
    20. if (cnt === 0 && !node.left && !node.right) {
    21. res.push([...path]); // 不能写res.push(path), 要深拷贝
    22. return;
    23. }
    24. if (!node.left && !node.right) return; // 遇到叶子节点而没有找到合适的边,直接返回
    25. // 左 (空节点不遍历)
    26. if (node.left) {
    27. path.push(node.left.val);
    28. traverse(node.left, cnt - node.left.val, path); // 递归
    29. path.pop(); // 回溯
    30. }
    31. // 右 (空节点不遍历)
    32. if (node.right) {
    33. path.push(node.right.val);
    34. traverse(node.right, cnt - node.right.val, path); // 递归
    35. path.pop(); // 回溯
    36. }
    37. return;
    38. };
    39. if (!root) return res;
    40. traverse(root, targetSum - root.val, [root.val]); // 把根节点放进路径
    41. return res;
    42. };

    image.png