[LeetCode/Kotlin]Easy - 938. Range Sum of BST

2023. 5. 23. 09:22LeetCode/Kotlin | Easy

728x90
반응형

[LeetCode/Kotlin]Easy - 938. Range Sum of BST

 

Range Sum of BST - LeetCode

Can you solve this real interview question? Range Sum of BST - Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high].   Example 1: [https://assets.l

leetcode.com

문제


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

Example 1:

Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
Output: 32
Explanation: Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.

Example 2:

Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
Output: 23
Explanation: Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23.

풀이


나의 풀이법

최종 소스코드

  1. 현재 root의 값이 low와 high 사이에 있으면 answer에 값을 더한다.
  2. 그리고 현재 root의 left와 right를 재귀로 호출하여 1을 반복한다.
class Solution {
    fun rangeSumBST(root: TreeNode?, low: Int, high: Int): Int {
        var answer = 0
        root?.let {
            if (it.`val` in low..high) answer += it.`val`
            answer += rangeSumBST(it.left, low, high)
            answer += rangeSumBST(it.right, low, high)
        }
        return answer
    }
}
728x90
반응형