반응형
https://leetcode.com/problems/range-sum-of-bst/
Range Sum of BST - LeetCode
Can you solve this real interview question? Range Sum of BST - Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high]. Example 1: [https://assets.l
leetcode.com
트리를 재귀적으로 순회하면서 범위 내의 합을 구해줍니다.
현재 노드의 값이 low 보다 작다면, 노드의 우측 하위 노드만 탐색해줍니다.
현재 노드의 값이 high 보다 크다면, 노드의 좌측 하위 노드만 탐색해줍니다.
class Solution {
public:
int rangeSumBST(TreeNode* root, int low, int high) {
if(!root) return 0;
if(root->val < low) return rangeSumBST(root->right, low, high);
if(root->val > high) return rangeSumBST(root->left, low, high);
return root->val + rangeSumBST(root->left, low, high) + rangeSumBST(root->right, low, high);
}
};
반응형
'Algorithm' 카테고리의 다른 글
LeetCode 2225. Find Players With Zero or One Losses (0) | 2024.01.15 |
---|---|
LeetCode 1347. Minimum Number of Steps to Make Two Strings Anagram (0) | 2024.01.13 |
LeetCode 446. Arithmetic Slices II - Subsequence (0) | 2024.01.08 |
LeetCode 2125. Number of Laser Beams in a Bank (0) | 2024.01.06 |
LeetCode 2870. Minimum Number of Operations to Make Array Empty (0) | 2024.01.04 |