[LeetCode] Range Sum of BST

아르당·5일 전

LeetCode

목록 보기
203/211
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

이진 탐색 트리의 root 노드와 두 정수 low 및 high가 주어졌을 때, [low, high] 범위 내에 있는 모든 노드의 값의 합을 반환해라.

Example

#1

Input: root = [10, 5, 14, 3, 7, null, 18], low = 7, high = 15
Output: 32
Explanation: 노드 7, 10, 15는 [7, 15] 범위 내에 있다. 7 + 10 + 15 = 32이다.

#2

Input: root = [10, 5, 15, 3, 7, 13, 18, 1, null, 6], low = 6, high = 10
Output: 23
Explanation: 노드 6, 7, 10은 [6, 10] 범위 내에 있다. 6 + 7 + 10 = 23이다.

Constraints

  • 트리에 노드의 수는 [1, 2 * 10^4] 범위에 있다.
  • 1 <= Node.val <= 10^5
  • 1 <= low <= high <= 10^5
  • 모든 Node.val은 고유하다.

Solved

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int rangeSumBST(TreeNode root, int low, int high) {
        if(root == null){
            return 0;
        }

        int curr = (root.val >= low && root.val <= high) ? root.val : 0;
        int left = rangeSumBST(root.left, low, high);
        int right = rangeSumBST(root.right, low, high);

        return curr + left + right;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글