【LeetCode】938. Range Sum of BST 解題報告(Python)
阿新 • • 發佈:2018-11-17
作者: 負雪明燭
id: fuxuemingzhu
個人部落格: http://fuxuemingzhu.cn/
目錄
題目地址:https://leetcode.com/contest/weekly-contest-110/problems/range-sum-of-bst/
題目描述
Given the root
node of a binary search tree, return the sum of values of all nodes with value between L
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.
題目大意
找出一個BST中,計算在[L,R]雙閉區間內的所有節點的值的和。
解題方法
遞迴
看見BST,就想起來它特殊的性質。所以這個題肯定能用上性質。
如果root不存在,返回0。如果root節點在[L,R]內,那麼把結果加上root的值,然後再分別加上左右子樹的值。為什麼?因為這個時候左右子樹都可能存在滿足[L,R]區間,所以必須都加上。
如果root的值比L還小,說明左子樹一定不會滿足[L,R]區間,那麼直接向右邊找就行。
如果root的值比R還大,說明右子樹一定不會滿足[L,R]區間,那麼直接向左邊找就行。
時間複雜度是O(N),空間複雜度是O(1)。
# 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
res = 0
if L <= root.val <= R:
res += root.val
res += self.rangeSumBST(root.left, L, R)
res += self.rangeSumBST(root.right, L, R)
elif root.val < L:
res += self.rangeSumBST(root.right, L, R)
elif root.val > R:
res += self.rangeSumBST(root.left, L, R)
return res
日期
2018 年 11 月 11 日 —— 剁手節快樂