알고리즘
Range of Sum BST (leetcode 938) 문제
뮹뭉묵목몽묭
2019. 8. 10. 00:27
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
Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).
The binary search tree is guaranteed to have unique values.
Example 1:
Input: root = [10,5,15,3,7,null,18], L = 7, R = 15 Output: 32
Example 2:
Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10 Output: 23
Note:
- The number of nodes in the tree is at most 10000.
- The final answer is guaranteed to be less than 2^31.
같단히 말해서 L 과 R 사이에 있는 모든 노드들의 합을 구하는 문제이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
class Solution {
public int rangeSumBST(TreeNode root, int L, int R) {
//노드가null 일경우 0을 리턴
if (root==null) {
return 0;
}
//노드가 L와 R사이에 있을경우 해당 노드 값 left와 right 모두 재귀 함수를 호출
if(root.val >= L && root.val <= R) {
return root.val + rangeSumBST(root.left, L, R) + rangeSumBST(root.right, L, R);
//노드가 L보다 작을 경우 노드의 오른쪽 값을 대입해서 재귀 함수를 호출
} else if(root.val<L) {
return rangeSumBST(root.right, L, R);
// 그 반대일 경우
} else {
return rangeSumBST(root.left, L ,R);
}
}
}
|
cs |