资讯专栏INFORMATION COLUMN

11.leetcode Range Sum of BST

shiweifu / 1094人阅读

1. 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.
#### 1. 例子

Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
Output: 32
Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
Output: 23
2. 我的解法
var rangeSumBST = function(root, L, R) {
    let sum =0
   sum = bstSun(sum, L, R, root)
    return sum
};


var bstSun = function(sum, L, R, node) {
    if(node !== null) {
        if(node.val<=R&&node.val>=L){
            sum += node.val
        }
        sum = bstSun(sum, L, R, node.left)
        sum = bstSun(sum, L, R, node.right)
    }
    return sum
} 
3. 其他解法
class Solution:
    def rangeSumBST(self, root, L, R):
        if not root: return 0
        l = self.rangeSumBST(root.left, L, R)
        r = self.rangeSumBST(root.right, L, R)
        return l + r + (L <= root.val <= R) * root.val

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/103571.html

相关文章

  • 315. Count of Smaller Numbers After Self

    摘要:题目链接的题,用来做,这种求有多少的题一般都是。里多加一个信息表示以为的节点数。也可以做,因为是统计有多少的,其实就是求从最小值到的。的是,要做一个映射,把的值映射到之间。所以先把给一下,用一个来做映射。还有的方法,参考 315. Count of Smaller Numbers After Self 题目链接:https://leetcode.com/problems... divi...

    cnio 评论0 收藏0
  • 493. Reverse Pairs

    摘要:题目链接和还有是一类题,解法都差不多。可以做,但是这道题如果输入是有序的,简单的会超时,所以得用来做。算的方法是比如给的例子,现在分成了左右两部分,拿两个指针和。 493. Reverse Pairs 题目链接:https://leetcode.com/problems... 和Count of Smaller Numbers After Self还有count of range su...

    acrazing 评论0 收藏0
  • 前端 | 每天一个 LeetCode

    摘要:在线网站地址我的微信公众号完整题目列表从年月日起,每天更新一题,顺序从易到难,目前已更新个题。这是项目地址欢迎一起交流学习。 这篇文章记录我练习的 LeetCode 题目,语言 JavaScript。 在线网站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公众号: showImg(htt...

    张汉庆 评论0 收藏0
  • leetcode 315 Count of Smaller Numbers After Self

    摘要:我们建立的,其中解决重复值的问题,记录左子树的节点数。给定要找的点,这里的规律就是,往右下走,说明当前点和当前的的左子树的值全部比小。我们走到要向右,这是左子树没变化,这里也不变。 题目细节描述参看leetcode。 今天的重头戏 LC315 Count of Smaller Numbers After Self.在讲这个题目之前,请思考这个问题。在BST找到所有比Node P小的节点...

    Little_XM 评论0 收藏0
  • Search Range in BST

    Given two values k1 and k2 (where k1 < k2) and a root pointer to a Binary Search Tree. Find all the keys of tree in range k1 to k2. i.e. print all x such that k1 k2root >= left bound ----> search unti...

    godruoyi 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<