给定二叉搜索树的根结点 root,返回 L 和 R(含)之间的所有结点的值的和。
二叉搜索树保证具有唯一的值。
示例 1:
输入:root = [10,5,15,3,7,null,18], L = 7, R = 15
输出:321.利用BST中序遍历有序这一特点
2.根据BST的性质
# 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 not root:
return 0
def t(root):
if not root:
return 0
t(root.left)
if L<=root.val<=R:
self.res += root.val
t(root.right)
self.res = 0
t(root)
return self.res
# 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):
if not root:
return 0
if root.val < L:
return self.rangeSumBST(root.right, L, R)
if root.val > R:
return self.rangeSumBST(root.left, L, R)
return root.val +self.rangeSumBST(root.left, L, R)+self.rangeSumBST(root.right, L, R)
来源:CSDN
作者:p0ther
链接:https://blog.csdn.net/qq_36328915/article/details/104173939