Saturday, March 6, 2021

Range sum BST

Given the root node of a binary search tree, return the sum of values of all nodes with a value in the range [low, high].

 

Example 1:

Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
Output: 32

class Solution {

public:

    int rangeSumBST(TreeNode* root, int low, int high) {

        int ans = 0;

        helper(root, low, high, ans);

        return ans;

    }

    

    void helper(TreeNode* root, int low, int high, int& ans) {

        if (root == NULL) {

            return;

        }

        helper(root -> left, low, high, ans);

        if (root -> val >= low && root -> val <= high) {

            ans += root -> val;

        } else if (root -> val > high) {

            return;

        }

        helper(root -> right, low, high, ans);

    }

};

No comments:

Post a Comment