문제
Given the
root
of a binary tree and an integer targetSum
, return all root-to-leaf paths where the sum of the node values in the path equals targetSum
. Each path should be returned as a list of the node values, not node references.A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.

Constraints:
- The number of nodes in the tree is in the range
[0, 5000]
.
1000 <= Node.val <= 1000
1000 <= targetSum <= 1000
풀이
재영
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @param {number} targetSum * @return {number[][]} */ class Q { constructor() { this.arr = []; this.front = 0; this.rear = 0; } enqueue(val) { this.arr.push(val); this.rear += 1; } dequeue() { const value = this.arr[this.front]; delete this.arr[this.front] this.front += 1; return value; } get length() { return this.rear - this.front } } const nodes = ['left', 'right']; const pathSum = (root, targetSum) => { const checkLeaf = (n) => !(n && nodes.some((direction) => n[direction])) if (checkLeaf(root)) { // 예외처리 1 return root?.val === targetSum ? [[root?.val]] : [] } const result = []; const queue = new Q(); queue.enqueue([0, [], root]) while (queue.length) { let [total, paths, now] = queue.dequeue(); total += now.val; paths.push(now.val); if (checkLeaf(now)) { if (targetSum === total) { result.push(paths) } } nodes.forEach((direction) => { if (now[direction] !== null) { queue.enqueue([total, [...paths], now[direction]]) } }) } return result; };
효성
var pathSum = function(root, targetSum) { if(!root) { return []; } const answer = []; const dfs = (node, sum, nodePath) => { if(!node.left && !node.right) { const total = sum + node.val; if(total === targetSum) { answer.push([...nodePath, node.val]); } return; } node.right && dfs(node.right, sum + node.val, [...nodePath, node.val]); node.left && dfs(node.left, sum + node.val, [...nodePath, node.val]); } dfs(root, 0, []); return answer; };
- 메모리 좀 더 좋게 해봤어요.
var pathSum = function(root, targetSum) { const answer = []; if(!root) { return answer; } const dfs = (node, sum, nodePath) => { if(!node.left && !node.right) { const total = sum + node.val; if(total === targetSum) { answer.push([...nodePath, node.val]); } return; } nodePath.push(node.val); node.right && dfs(node.right, sum + node.val, nodePath); node.left && dfs(node.left, sum + node.val, nodePath); nodePath.pop(); } dfs(root, 0, []); return answer; };