Leetcode 938.二叉搜索树的范围和(Range Sum of BST)

Leetcode 938.二叉搜索树的范围和

1 题目描述(Leetcode题目链接

  给定二叉搜索树的根结点 root,返回 L 和 R(含)之间的所有结点的值的和。二叉搜索树保证具有唯一的值。

输入:root = [10,5,15,3,7,null,18], L = 7, R = 15
输出:32
输入:root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
输出:23

提示:

  • 树中的结点数量最多为 10000 10000 个。
  • 最终的答案保证小于 2 3 1 2^31

2 题解

  基于二叉搜索树的性质可以比较容易地想到递归实现。更多信息可见二叉搜索树

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:
        if not root:
            return 0
        if root.val < L:
            return self.rangeSumBST(root.right, L, R)
        elif root.val > R:
            return self.rangeSumBST(root.left, L, R)
        else:
            return root.val + self.rangeSumBST(root.left, L, R) + self.rangeSumBST(root.right, L, R)

中序遍历也是可以的。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:
        stack = []
        retv = 0
        while root or stack:
            while root:
                stack.append(root)
                root = root.left
            root = stack.pop()
            if root.val > R:
                return retv
            if root.val >= L:
                retv += root.val
            root = root.right
        return retv
发布了264 篇原创文章 · 获赞 63 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_39378221/article/details/105023665
今日推荐