반응형
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 으로 초기화되지 않는 문제가 발생했다. 그래서 함수를 선언 후, 함수안에서 재귀적으로 풀어주었다.
반응형
'알고리즘문제' 카테고리의 다른 글
프로그래머스 - 없는 숫자 더하기 (0) | 2022.09.17 |
---|---|
1630. Arithmetic Subarrays (0) | 2022.03.29 |
LeetCode 1528.Shuffle String (0) | 2021.11.21 |
문자열 내 마음대로 풀어보기 - 프로그래머스 (0) | 2021.10.03 |
시저 암호 - 프로그래머스 (0) | 2021.09.30 |