【LeetCode】938. Range Sum of BST 解题报告(Python & C++)
作者: 负雪明烛
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
and 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
也可以直接判断寻找的方向,能简化一点代码。如果root节点小于R,说明右边可以继续搜索;如果root节点大于L,说明左边可以继续搜索。
# 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
"""
res = [0]
self.dfs(root, L, R, res)
return res[0]
def dfs(self, root, L, R, res):
if not root:
return
if L <= root.val <= R:
res[0] += root.val
if root.val < R:
self.dfs(root.right, L, R, res)
if root.val > L:
self.dfs(root.left, L, R, res)
C++版本的代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int rangeSumBST(TreeNode* root, int L, int R) {
dfs(root, L, R);
return res;
}
private:
int res = 0;
void dfs(TreeNode* root, int L, int R) {
if (root == nullptr) return;
if (root->val <= R && root->val >= L) res += root->val;
if (root->val > L) dfs(root->left, L, R);
if (root->val < R) dfs(root->right, L, R);
}
};
日期
2018 年 11 月 11 日 —— 剁手节快乐
2018 年 12 月 2 日 —— 又到了周日
【LeetCode】938. Range Sum of BST 解题报告(Python & C++)的更多相关文章
- Leetcode 938. Range Sum of BST
import functools # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, ...
- LeetCode #938. Range Sum of BST 二叉搜索树的范围和
https://leetcode-cn.com/problems/range-sum-of-bst/ 二叉树中序遍历 二叉搜索树性质:一个节点大于所有其左子树的节点,小于其所有右子树的节点 /** * ...
- 【Leetcode_easy】938. Range Sum of BST
problem 938. Range Sum of BST 参考 1. Leetcode_easy_938. Range Sum of BST; 完
- 【LeetCode】303. Range Sum Query - Immutable 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 解题方法 保存累积和 日期 题目地址:https://leetcode. ...
- 【LeetCode】450. Delete Node in a BST 解题报告 (Python&C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 迭代 日期 题目地址:https://leetcode ...
- [LeetCode] 307. Range Sum Query - Mutable 解题思路
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...
- 938. Range Sum of BST
Given the root node of a binary search tree, return the sum of values of all nodes with value betwee ...
- 【LeetCode】654. Maximum Binary Tree 解题报告 (Python&C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcode ...
- 【LeetCode】784. Letter Case Permutation 解题报告 (Python&C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 回溯法 循环 日期 题目地址:https://leet ...
随机推荐
- BaiduPCS-Go----百度云下载工具
1.网页登录百度网盘:https://pan.baidu.com/2.百度输入法生成:http://pcs.baidu.com/rest/2.0/pcs/file?app_id=265486& ...
- 什么是总线、总线的类型、局部总线、局部总线类型和什么是接口方式?什么是IDE?什么是SCSI?
在安装电脑系统时,进行内核配置时涉及到各种总线类型,有必要了解一下什么是总线.总线的类型.局部总线.局部总线类型和接口方式. 1)总线总线是一组通信线.在机器内部, 各部件通过总线连接; 对于外部设备 ...
- python基础实战
字符串的互相转换 字典的排序 字典的排序可以直接把,key值或者,values拿出来排序 也可以用dict.items拿出所有的key,value的值再加key=lambda x:x[1] 来排序. ...
- java9 模块化 jigsaw
java9并没有在语言层面做出很多改变,而是致力于一些新特性,如模块化,其核心就是解决历史遗留问题,为以后的jar包森林理清道路.模块化是一个很大的命题,就不讲那么细致了,关于java9的特性也有很多 ...
- Spark(七)【RDD的持久化Cache和CheckPoint】
RDD的持久化 1. RDD Cache缓存 RDD通过Cache或者Persist方法将前面的计算结果缓存,默认情况下会把数据以缓存在JVM的堆内存中.但是并不是这两个方法被调用时立即缓存,而是 ...
- 【DFS与BFS】洛谷 P1135 奇怪的电梯
题目:奇怪的电梯 - 洛谷 (luogu.com.cn) 因为此题数据范围较小,有dfs及bfs等多种做法. DFS 比较正常的dfs,注意vis数组一定要回溯,不然会漏情况 例如这个数据 11 1 ...
- OpenStack之之一: 快速添加计算节点
根据需求创建脚本,可以快速添加节点#:初始化node节点 [root@node2 ~]# systemctl disable NetworkManager [root@node2 ~]# vim /e ...
- LocalDate计算两个日期相差天数
import org.apache.commons.lang.StringUtils; import java.time.LocalDate; import java.time.ZoneId; imp ...
- Dubbo多注册中心
一.创建提供者08-provider-registers (1) 创建工程 直接复制05-provider-group工程,并命名为08-provider-registers (2) 修改配置文件 二 ...
- shell条件测试语句实例-测试apache是否开启
终于理解了shell条件测试语句"!="和"-n"的用法区别,于是有了如下的shell脚本,做为练习. 第一种方法:测试apache是否开启?字符串测试 #!/ ...