Path Sum III - LeetCode
Can you solve this real interview question? Path Sum III - Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum. The path does not need to start or end at the roo
leetcode.com
< 문제 간단설명 >
주어진 트리내에서 targetSum을 만족하는 subtree가 몇개가 존재하는지 반환하는 문제이다.
/**
* 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 count = 0;
const isTargetSum = (node, sum) => {
if(node === null) {
return;
}
// 현재 노드의 값과 targetSum이 같다면,
// 현재 노드만 더하면 targetSum이 되는것이므로 count + 1
if(sum + node.val === targetSum) {
count += 1;
}
// 왼쪽 subtree를 탐색하면서 targetSum에서 현재 노드의 값을 빼줌
isTargetSum(node.left, sum + node.val);
// 오른쪽 subtree를 탐색하면서 targetSum에서 현재 노드의 값을 빼줌
isTargetSum(node.right, sum + node.val);
}
const DFS = (node) => {
if(node === null) {
return;
}
DFS(node.left);
DFS(node.right);
isTargetSum(node, 0);
}
DFS(root);
return count;
};
'PS > LeetCode' 카테고리의 다른 글
LeetCode / Binary Search / 33번 / Search in Rotated Sorted Array / JS (0) | 2023.04.28 |
---|---|
LeetCode / Binary Search / 74번 / Search a 2D Matrix / JS (0) | 2023.04.28 |
LeetCode / Tree / 543번 / Diameter of Binary Tree / JS (0) | 2023.04.28 |
LeetCode / Tree / 110번 / Balanced Binary Tree / JS (0) | 2023.04.28 |