|
| 1 | +/** |
| 2 | + * 113. Path Sum II |
| 3 | + * https://leetcode.com/problems/path-sum-ii/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where |
| 7 | + * the sum of the node values in the path equals targetSum. Each path should be returned as a |
| 8 | + * list of the node values, not node references. |
| 9 | + * |
| 10 | + * A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a |
| 11 | + * node with no children. |
| 12 | + */ |
| 13 | + |
| 14 | +/** |
| 15 | + * Definition for a binary tree node. |
| 16 | + * function TreeNode(val, left, right) { |
| 17 | + * this.val = (val===undefined ? 0 : val) |
| 18 | + * this.left = (left===undefined ? null : left) |
| 19 | + * this.right = (right===undefined ? null : right) |
| 20 | + * } |
| 21 | + */ |
| 22 | +/** |
| 23 | + * @param {TreeNode} root |
| 24 | + * @param {number} targetSum |
| 25 | + * @return {number[][]} |
| 26 | + */ |
| 27 | +var pathSum = function(root, targetSum) { |
| 28 | + if (!root) return []; |
| 29 | + return traverse([], targetSum, root); |
| 30 | +}; |
| 31 | + |
| 32 | +function traverse(result, targetSum, node, history = []) { |
| 33 | + const values = [...history, node.val]; |
| 34 | + |
| 35 | + if (!node.left && !node.right && values.reduce((sum, n) => sum + n, 0) === targetSum) { |
| 36 | + result.push(values); |
| 37 | + } |
| 38 | + |
| 39 | + if (node.left) traverse(result, targetSum, node.left, values); |
| 40 | + if (node.right) traverse(result, targetSum, node.right, values); |
| 41 | + |
| 42 | + return result; |
| 43 | +} |
0 commit comments