알고리즘문제

938. Range Sum of BST

단점이없어지고싶은개발자 2022. 3. 14. 10:59
반응형

 

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

 

Range Sum of BST - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} low
 * @param {number} high
 * @return {number}
 */


var rangeSumBST = function(root, low, high) {
    let rangeSum = 0;

    range(root, low, high)
    
    function range(root, low, high) {
        if (root === null) {
            return;
        }
    
        if (root.val) {
            if (root.val >= low && root.val <= high) {
                rangeSum += root.val;
            }
        }
        
        range(root.left, low, high);
        range(root.right, low, high);
    }
    
    
    return rangeSum;
};

처음에는 합계해주는 부분을 밖에 스코프에 놓고 했었는데 중간에 정답 처리에서 값이 0 으로 초기화되지 않는 문제가 발생했다. 그래서 함수를 선언 후, 함수안에서 재귀적으로 풀어주었다.

반응형