Given the root node of a binary search tree, return the sum of values of all nodes with a value in the range [low, high].

Example 1:

Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
Output: 32

Example 2:

Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
Output: 23

Constraints:

  • The number of nodes in the tree is in the range [1, 2 * 10^4].
  • 1 <= Node.val <= 10^5
  • 1 <= low <= high <= 10^5
  • All Node.val are unique.

Solution in python:

# 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, low: int, high: int) -> int:
        def traverse(root):
            if root == None:
                return []
            else:
                temp = []
                left = traverse(root.left)
                temp.extend(left)
                temp.append(root.val)
                right = traverse(root.right)
                temp.extend(right)
                return temp
        alist = traverse(root)
        i = 0
        j = len(alist)-1
        while i < len(alist):
            if alist[i] < low:
                i += 1
            else: break
        while j > -1:
            if alist[j] > high:
                j -= 1
            else: break
        return sum(alist[i:j+1])
最后修改日期: 2021年2月25日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。