-
[Algorithm] LeetCode - 113. Path Sum II (DFS)Alogorithm 2022. 2. 13. 19:48반응형
LeetCode 문제입니다.
[문제설명]
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.
번역)
Binary Tree의 root와 정수 targetSum이 주어지면 경로에 있는 node 값의 합이 targetSum과 같은 모든 root-leaf 경로를 반환합니다. 각 경로는 node 참조가 아닌 node 값 목록으로 반환되어야 합니다. root에서 leaf node 경로는 root에서 시작하여 임의의 leaf node에서 끝나는 경로입니다. Leaf node는 자식이 없는 node입니다.
-> 각 leaf node까지 도달한다.
-> root node -> leaf node까지의 경로 배열에서 summation 후 targetSumr과 같으면 answer에 추가
Topic: Backtracking, Tree, Depth First Search, Binary Tree
Level: Medium
Accepted 542,303 / Submissions 1,017,491
[제한사항]
- The number of nodes in the tree is in the range [0, 5000].
- -1000 <= Node.val <= 1000
- -1000 <= targetSum <= 1000
[입출력]
예시 1
Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 Output: [[5,4,11,2],[5,8,4,5]] Explanation: There are two paths whose sum equals targetSum: 5 + 4 + 11 + 2 = 22 5 + 8 + 4 + 5 = 22
예시 2
Input: root = [1,2,3], targetSum = 5 Output: []
예시 2
Input: root = [1,2], targetSum = 0 Output: []
[문제풀이]
/** * 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[][]} */ var pathSum = function(root, targetSum) { let answer = [] const checkLeaf = (node) => (node.left === null && node.right === null) // if root is empty, return empty answer if (!root) return answer // if root node equals targetSum, push this value to the answer if (root.val === targetSum && checkLeaf(root)) return [[root.val]] const dfs = (node, path, pathSum) => { if(!node || node.val === null) return const summation = pathSum + node.val const thisPath = path.concat(node.val) if (summation === targetSum && checkLeaf(node)) { answer.push(thisPath) } else { dfs(node.left, thisPath, summation) dfs(node.right, thisPath, summation) } } dfs(root.left, [root.val], root.val); dfs(root.right, [root.val], root.val); return answer };
Idea:
1. left child node부터 dfs 함수 call
2. Leaf node이고 targetSum과 경로상 노드들의 합이 같다면 anwer push
3. 아니라면 dfs call
[Performance]
반응형'Alogorithm' 카테고리의 다른 글
[Algorithm] LeetCode - 229. Majority Element II, [Array, Hash, Sorting] (0) 2022.04.18 [Algorithm] LeetCode - 102. Binary Tree Level Order Traversal (BFS) (0) 2022.02.13 [Algorithm] 시간 복잡도 (0) 2022.01.23 [Algorithm] LeetCode - 1817. Finding the Users Active Minutes(Hash) (0) 2022.01.23 [Algorithm] LeetCode - 1641. Count Sorted Vowel Strings(Dynamic Programming) (0) 2022.01.23