[leetcode] 938. Range Sum of BST

Description

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.

Example 1:

Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
Output: 32

Example 2:

Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
Output: 23

Note:

  1. The number of nodes in the tree is at most 10000.
  2. The final answer is guaranteed to be less than 2^31.

分析

题目的意思是:求出一个二叉排序树的满足区间范围[L,R]的和,这道题可以用递归的方式来解决,如果当前的结点的值小于L,说明左分支都不符合条件,结果只可能在右分支。如果大于R,说明右分支不符合条件。如果在[L,R]之间,则说明左右分支都还右结点的值符合条件,因此左右两个分支都需要递归遍历。如果能够想到这个就可以做出来了。

代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:
        if(root is None):
            return 0
        
        if(root.val<L):
            return self.rangeSumBST(root.right,L,R)
        elif(root.val>R):
            return self.rangeSumBST(root.left,L,R)
        elif(root.val>=L and root.val<=R):
            return root.val+self.rangeSumBST(root.left,L,R)+self.rangeSumBST(root.right,L,R)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值