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
思路:
讲道理刚看到这个题目还是有点懵逼的,仔细考虑一下还是觉得题目的意思应该是先对这棵树进行中序遍历 ,再将中序遍历的结果中的L与R之间的值输出。
例一中树的结构为:
中序遍历结果为[3 5 7 10 15 18],L与R之间的和即为32
例二中的树的结构为:
中序遍历结果为[1 3 5 6 7 10 13 15 18],L与R之间的和即为23
# 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
"""
if root == None:
return 0
left = self.rangeSumBST(root.left, L, R)
if root.val >= L and root.val <= R:
val = root.val
else:
val = 0
right = self.rangeSumBST(root.right, L, R)
return left + val +right