给你二叉树的根节点 root 和一个整数目标和 targetSum,找出所有从根节点到叶子节点路径总和等于给定目标和的路径。
解析
1 2 3 4 5 6 7 8 9 10 11 12 13
| var pathSum = function (root, targetSum) { const result = []; function dfs(node, remaining, path) { if (!node) return; path.push(node.val); if (!node.left && !node.right && remaining === node.val) result.push([...path]); dfs(node.left, remaining - node.val, path); dfs(node.right, remaining - node.val, path); path.pop(); } dfs(root, targetSum, []); return result; };
|