0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

LeetCode日本語修行14日目- [938-指定範囲内二分探索木のSUM]

Posted at

###Range Sum of BST
#####参考:https://leetcode.com/problems/range-sum-of-bst/
###問題の内容:
###例:
例1:
Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
Output: 32

    10
  5    15
3   7     18 

例2:
Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
Output: 23

     10
   5    15
 3  7  13 18
1  6

###ヒント:
The number of nodes in the tree is in the range [1, 2 * 104].
1 <= Node.val <= 105
1 <= low <= high <= 105
All Node.val are unique.


DFSを使って、範囲内のvalueを全部プラスするなら、解決できます。

/**
 * Example:
 * var ti = TreeNode(5)
 * var v = ti.`val`
 * Definition for a binary tree node.
 * class TreeNode(var `val`: Int) {
 *     var left: TreeNode? = null
 *     var right: TreeNode? = null
 * }
 */
class Solution {
    fun rangeSumBST(root: TreeNode?, low: Int, high: Int): Int {
        if(root == null){
            return 0
        }
        if(root.`val` < low){
            return rangeSumBST(root?.right,low,high)
        }
        if(root.`val` > high  ){
            return rangeSumBST(root?.left,low,high)
        }
        return  root.`val` + rangeSumBST(root?.right,low,high) +  rangeSumBST(root?.left,low,high)
    }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?