Leetcode 938 二叉搜索树的范围和
2019-07-14 本文已影响0人
禾木清清
题目
给定二叉搜索树的根结点 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
提示:
树中的结点数量最多为 10000 个。
最终的答案保证小于 2^31
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/range-sum-of-bst
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
本题是要计算树中给定范围内的所有节点的和。
- 将root的值和范围进行比较,如果在范围内就相加根的值,然后对左右子树进行相加
- 递归的将左右和root分别比较,< L只保留右子树,否则左子树
- 返回值
代码 284ms
# 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
"""
total = 0
if not root:
return total
if root.val < L:
total += self.rangeSumBST(root.right, L, R)
elif root.val > R:
total += self.rangeSumBST(root.left, L, R)
else:
total += root.val
total += self.rangeSumBST(root.left, L, R)
total += self.rangeSumBST(root.right, L, R)
return total