반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- Props
- React
- priority_queue
- state
- server
- UE5
- count
- MySQL
- axios
- routes
- c++
- BinaryTree
- Callback
- nodeJS
- leetcode
- Navigation
- array
- Context
- treenode
- component
- DP
- css
- node.js
- 비트연산
- bit
- map
- route
- queue
- event
- JSX
Archives
- Today
- Total
우사미 코딩
[Leetcode] 437. Path Sum III 본문
반응형
1. 문제링크
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
2. Key Point - targetSum은 어디에나 존재할 수 있다, 모든 노드를 탐색하자
이 꼭 시작과 끝이 root에서 leaf까지의 sum이 아니어도 된다.
현재까지의 sum이 targetSum이더라도 아래 노드를 계속 탐색한다 (핑크색)
3. Solution
class Solution {
public:
int ans = 0;
void solve(TreeNode* node, long long sum){
if(!node) return;
if(node->val == sum){
ans++;
}
solve(node->left, sum - node->val);
solve(node->right, sum - node->val);
}
int pathSum(TreeNode* root, int targetSum) {
if(!root) return 0;
solve(root, targetSum);
pathSum(root->left, targetSum);
pathSum(root->right, targetSum);
return ans;
}
};
반응형
'Leetcode' 카테고리의 다른 글
[Leetcode] 621. Task Scheduler (0) | 2023.05.26 |
---|---|
[Leetcode] 33. Search in Rotated Sorted Array - binary search (0) | 2023.05.23 |
[Leetcode] 543. Diameter of Binary Tree (0) | 2023.05.23 |
[Leetcode] 110. Balanced Binary Tree (0) | 2023.05.23 |
[Leetcode] 953. Verifying an Alien Dictionary - hash map (0) | 2023.05.22 |
Comments