주어진 이진 트리에서 특정 합계(targetSum)를 갖는 경로의 개수를 찾는 문제입니다. 경로는 부모에서 자식으로만 이동할 수 있습니다.
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 root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
Example 1:
Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
Output: 3
Explanation: The paths that sum to 8 are shown.
Example 2:
Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
Output: 3
풀이과정 설명:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int pathSum(TreeNode root, int targetSum) {
if(root == null) return 0;
return countPaths(root, targetSum)
+ pathSum(root.left, targetSum)
+ pathSum(root.right, targetSum);
}
public int countPaths(TreeNode node, int targetSum){
if(node == null) return 0;
int count = 0;
if(node.val == targetSum) count++;
count += countPaths(node.left, targetSum - node.val);
count += countPaths(node.right, targetSum - node.val);
return count;
}
}
2130. Maximum Twin Sum of a Linked List (0) | 2023.11.19 |
---|---|
328. Odd Even Linked List (0) | 2023.11.18 |
206. Reverse Linked List (0) | 2023.11.18 |
649. Dota2 Senate (0) | 2023.11.18 |
933. Number of Recent Calls (0) | 2023.11.17 |