본문 바로가기

Algorithm/DFS

(C++) - LeetCode (easy) 938. Range Sum of BST

반응형

https://leetcode.com/problems/range-sum-of-bst/description/

 

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

재귀 구현 문제였습니다.

📕 풀이방법

📔 풀이과정

왼쪽 sub tree 의 정답 + 오른쪽 sub tree의 정답 을 더한 값을 sum에 저장합니다.현재 node값이 범위 내라면 sum에 root->val을 누적해 더해줍니다.매 재귀함수마다 sum을 반환합니다.


📕 Code

📔 C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int rangeSumBST(TreeNode* root, int low, int high) {
        if(root == NULL) return 0;
        int sum = rangeSumBST(root->left, low, high) + rangeSumBST(root->right, low, high);
        if (low <= root->val && root->val <= high) sum += root->val;
        return sum;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.