LeetCode-Python-938. 二叉搜索树的范围和

642 篇文章 23 订阅

给定二叉搜索树的根结点 root,返回 L 和 R(含)之间的所有结点的值的和。

二叉搜索树保证具有唯一的值。

 

示例 1:

输入:root = [10,5,15,3,7,null,18], L = 7, R = 15
输出:32

示例 2:

输入:root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
输出:23

 

提示:

  1. 树中的结点数量最多为 10000 个。
  2. 最终的答案保证小于 2^31

 

第一种思路:

麻瓜解法,直接把所有的节点找出来。

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def rangeSumBST(self, root, L, R):
        """
        :type root: TreeNode
        :type L: int
        :type R: int
        :rtype: int
        """
        
        self.res = 0
        def inorder(node):
            if not node:
                return
            
            inorder(node.left)
            if node.val >= L and node.val <= R:
                self.res += node.val
            inorder(node.right)
        inorder(root)
        return self.res 

第二种思路:

利用BST的性质递归。

先处理根节点,

然后判断一下要不要在右子树里找,

如果根节点的值都比R大了,那么右子树里的节点只会更大,就不用在右子树里找了,

所以在右子树里找的条件是root.val < R。

左子树同理。

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def rangeSumBST(self, root, L, R):
        """
        :type root: TreeNode
        :type L: int
        :type R: int
        :rtype: int
        """
        res = 0
        
        if not root:
            return 0
        if L <= root.val <= R:
            res += root.val
        if root.val < R:
            res += self.rangeSumBST(root.right, L, R)
        if root.val > L:
            res += self.rangeSumBST(root.left, L, R)
            
        return res
                

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值