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:
- The number of nodes in the tree is at most 10000.
- 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)