Range Sum of BST

ㅋㅋ·2022년 12월 7일
0

알고리즘-leetcode

목록 보기
64/135

바이너리 트리의 루트 노드와 최저값과 최대값을 받는다.

트리에서 해당 최저값 이상, 최대값 이하를 만족하는 값들의 합을 구하는 문제

/**
 * 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:
    void SumDSF(TreeNode* root, int &low, int &high, int &result)
    {
        if (root == NULL)
        {
            return;
        }

        if ((low <= root->val) && (root->val <= high))
        {
            result += root->val;
        }

        SumDSF(root->left, low, high, result);
        SumDSF(root->right, low, high, result);
    }

    int rangeSumBST(TreeNode* root, int low, int high) {
        
        int sum{0};
        
        SumDSF(root, low, high, sum);

        return sum;
    }
};

0개의 댓글