作者: 负雪明烛
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:

  1. The number of nodes in the tree is at most 10000.
  2. 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++)的更多相关文章

  1. Leetcode 938. Range Sum of BST

    import functools # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, ...

  2. LeetCode #938. Range Sum of BST 二叉搜索树的范围和

    https://leetcode-cn.com/problems/range-sum-of-bst/ 二叉树中序遍历 二叉搜索树性质:一个节点大于所有其左子树的节点,小于其所有右子树的节点 /** * ...

  3. 【Leetcode_easy】938. Range Sum of BST

    problem 938. Range Sum of BST 参考 1. Leetcode_easy_938. Range Sum of BST; 完

  4. 【LeetCode】303. Range Sum Query - Immutable 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 解题方法 保存累积和 日期 题目地址:https://leetcode. ...

  5. 【LeetCode】450. Delete Node in a BST 解题报告 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 迭代 日期 题目地址:https://leetcode ...

  6. [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 ...

  7. 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 ...

  8. 【LeetCode】654. Maximum Binary Tree 解题报告 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcode ...

  9. 【LeetCode】784. Letter Case Permutation 解题报告 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 回溯法 循环 日期 题目地址:https://leet ...

随机推荐

  1. echo 输出彩色字符

    借助echo的-e选项来实现,语法格式为 echo -e "\033[3xmsome things you want to print out.\033[0m" \033[3xm为 ...

  2. Linux软件安装管理:rpm与yum

    目录 1. rpm包的管理 1.1 介绍 1.2 rpm包的简单查询指令 1.3 rpm 包名的基本格式 1.4 rpm其它指令 1.5 卸载rpm包 1.6 安装rpm包 2. yum 2.1 说明 ...

  3. Python基础之列表内置方法

    目录 1. 列表 1.1 序列 1.2 通用的序列操作 1.3 列表的基本操作 1.4 列表方法 1. 列表 数据结构:以某种方式(如通过编号)组合起来的元素(如数,字符乃至其他数据结构)集合. 在p ...

  4. Excel-满足指定条件并且包含数字的单元格数目,DCOUNT()

    DCOUNT函数 函数名称:DCOUNT 主要功能:返回数据库或列表的列中满足指定条件并且包含数字的单元格数目. 使用格式:DCOUNT(database,field,criteria) 参数说明:D ...

  5. 修改unittest源码之tearDown

    需求 最近在写selenium自动化平台,想把每条用例后面都带上截图,最开始是每条用例加上封装好的截图函数,但是发现太麻烦,就决定加在tearDown函数里面,每条用例结束后执行截图操作. 那么问题来 ...

  6. 在Kubernetes上安装Percona XtraDB集群

    官方文档地址:https://www.percona.com/doc/kubernetes-operator-for-pxc/kubernetes.html 一.简介 Percona XtraDB C ...

  7. flink01--------1.flink简介 2.flink安装 3. flink提交任务的2种方式 4. 4flink的快速入门 5.source 6 常用算子(keyBy,max/min,maxBy/minBy,connect,union,split+select)

    1. flink简介 1.1 什么是flink Apache Flink是一个分布式大数据处理引擎,可以对有限数据流(如离线数据)和无限流数据及逆行有状态计算(不太懂).可以部署在各种集群环境,对各种 ...

  8. Vue相关,diff算法。

    1. 当数据发生变化时,vue是怎么更新节点的? 要知道渲染真实DOM的开销是很大的,比如有时候我们修改了某个数据,如果直接渲染到真实dom上会引起整个dom树的重绘和重排,有没有可能我们只更新我们修 ...

  9. 用户创建firefox配置文件

    1.打开cmd进放 firefox.exe所在的目录 如:D:\>cd D:\Mozilla Firefox 2.运行如命令:D:\Mozilla Firefox>firefox.exe ...

  10. 【Java 基础】Java Map中的Value值如何做到可以为任意类型的值

    Occasionally the average developer runs into a situation where he has to map values of arbitrary typ ...