这是悦乐书的第359次更新,第386篇原创

01 看题和准备

今天介绍的是LeetCode算法题中Easy级别的第221题(顺位题号是938)。给定二叉搜索树的根节点,返回节点值在[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。

  • 最终答案保证不到2^31。

02 第一种解法

既然给的是二叉搜索树,那么遍历节点我们就选取中序遍历的方式,这样最直接,存入List中,然后遍历List中的节点值,将节点值大于等于L且小于等于R的进行累加,最后返回sum即可。

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int rangeSumBST(TreeNode root, int L, int R) {
List<Integer> list = new ArrayList<Integer>();
helper(root, list);
int sum = 0;
for (Integer num : list) {
if (num >= L && num <= R) {
sum += num;
}
}
return sum;
} public void helper(TreeNode root, List<Integer> list){
if (root == null) {
return ;
}
helper(root.left, list);
list.add(root.val);
helper(root.right, list);
}
}

03 第二种解法

针对第一种解法,我们也可以使用迭代的方式来实现,借助

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int rangeSumBST(TreeNode root, int L, int R) {
List<Integer> list = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode tem = stack.pop();
if (tem != null) {
list.add(tem.val);
}
if (tem != null && tem.left != null) {
stack.push(tem.left);
}
if (tem != null && tem.right != null) {
stack.push(tem.right);
}
}
int sum = 0;
for (Integer num : list) {
if (num >= L && num <= R) {
sum += num;
}
}
return sum;
}
}

04 第三种解法

我们其实不用将节点值存起来后再统一处理,直接在遍历节点的时候,将在[L,R]范围内的节点值累加即可,最后返回sum。此解法是迭代的方式。

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int rangeSumBST(TreeNode root, int L, int R) {
int sum = 0;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode tem = stack.pop();
if (tem != null) {
if (tem.val >= L && tem.val <= R) {
sum += tem.val;
}
}
if (tem != null && tem.left != null) {
stack.push(tem.left);
}
if (tem != null && tem.right != null) {
stack.push(tem.right);
}
}
return sum;
}
}

05 第四种解法

针对第三种解法,我们也可以使用递归的方式。定义一个全局变量sum,依旧使用中序遍历的方式,将在[L,R]范围内的节点值累加,最后返回sum

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution { private Integer sum = 0; public int rangeSumBST(TreeNode root, int L, int R) {
if (root == null) {
return sum;
}
rangeSumBST(root.left, L, R);
if (root.val >= L && root.val <= R) {
sum += root.val;
}
rangeSumBST(root.right, L, R);
return sum;
}
}

06 第五种解法

针对第四种解法,我们也可以不使用全局变量,借助二叉搜索树节点值按照左根右的大小排列特性,如果当前节点值比L小,就往右边找,如果比R大,就往左边找,最后求和。

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution { public int rangeSumBST(TreeNode root, int L, int R) {
if (root == null) {
return 0;
}
if (root.val < L) {
return rangeSumBST(root.right, L, R);
}
if (root.val > R) {
return rangeSumBST(root.left, L, R);
}
return root.val + rangeSumBST(root.left, L, R) +
rangeSumBST(root.right, L, R);
}
}

07 小结

算法专题目前已连续日更超过七个月,算法题文章227+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。

以上就是全部内容,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!

LeetCode.938-范围内求二叉搜索树节点值之和(Range Sum of BST)的更多相关文章

  1. [Swift]LeetCode938. 二叉搜索树的范围和 | Range Sum of BST

    Given the root node of a binary search tree, return the sum of values of all nodes with value betwee ...

  2. 【python】Leetcode每日一题-二叉搜索树节点最小距离

    [python]Leetcode每日一题-二叉搜索树节点最小距离 [题目描述] 给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 . 示例1: 输入:root = [4 ...

  3. Java实现 LeetCode 783 二叉搜索树节点最小距离(遍历)

    783. 二叉搜索树节点最小距离 给定一个二叉搜索树的根节点 root,返回树中任意两节点的差的最小值. 示例: 输入: root = [4,2,6,1,3,null,null] 输出: 1 解释: ...

  4. [LeetCode] 272. Closest Binary Search Tree Value II 最近的二叉搜索树的值 II

    Given a non-empty binary search tree and a target value, find k values in the BST that are closest t ...

  5. LeetCode 96——不同的二叉搜索树

    1. 题目 2. 解答 以 \(1, 2, \cdots, n\) 构建二叉搜索树,其中,任意数字都可以作为根节点来构建二叉搜索树.当我们将某一个数字作为根节点后,其左边数据将构建为左子树,右边数据将 ...

  6. 【JavaScript】Leetcode每日一题-二叉搜索树的范围和

    [JavaScript]Leetcode每日一题-二叉搜索树的范围和 [题目描述] 给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和. 示例1: 输入: ...

  7. Leetcode 96. 不同的二叉搜索树

    题目链接 https://leetcode.com/problems/unique-binary-search-trees/description/ 题目描述 给定一个整数 n,求以 1 ... n ...

  8. LeetCode动画 | 1038. 从二叉搜索树到更大和树

    今天分享一个LeetCode题,题号是1038,标题是:从二分搜索树到更大和数. 题目描述 给出二叉搜索树的根节点,该二叉树的节点值各不相同,修改二叉树,使每个节点 node 的新值等于原树中大于或等 ...

  9. [LeetCode]96. 不同的二叉搜索树(DP,卡特兰数)

    题目 给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种? 示例: 输入: 3 输出: 5 解释: 给定 n = 3, 一共有 5 种不同结构的二叉搜索树: 1 3 3 2 1 \ ...

随机推荐

  1. 第四章 生命周期函数--36 结合Node手写JSONP服务器剖析JSONP原理

  2. 发送动态IP到邮件

    # -*-coding:utf8 -*- #!/usr/bin/python import smtplib from email.mime.text import MIMEText # IP impo ...

  3. visudo修改编辑器vim

    update-alternatives --config editor

  4. Word2Vec小心得

    今天终于想明白了分层softmax的作用: 哈夫曼树的作用是什么??用平均最小的长度编码!编码是为了解码成信息! 神经概率语言模型:有映射层,隐藏层,输出层,假设隐藏层是300维,输出层是和单词的数量 ...

  5. 【leetcode】1012. Numbers With Repeated Digits

    题目如下: Given a positive integer N, return the number of positive integers less than or equal to N tha ...

  6. 【leetcode】LCP 2. 分式化简

    题目如下: 有一个同学在学习分式.他需要将一个连分数化成最简分数,你能帮助他吗? 连分数是形如上图的分式.在本题中,所有系数都是大于等于0的整数. 输入的cont代表连分数的系数(cont[0]代表上 ...

  7. 【leetcode】1234. Replace the Substring for Balanced String

    题目如下: You are given a string containing only 4 kinds of characters 'Q', 'W', 'E' and 'R'. A string i ...

  8. mysql 递归查找所有子节点

    select dept_id from ( select t1.dept_id,t1.parent_id, if(find_in_set(parent_id, @pids) > 0, @pids ...

  9. jquery which事件 语法

    jquery which事件 语法 作用:which 属性指示按了哪个键或按钮.大理石平台精度等级 语法:event.whic 参数: 参数 描述 event     必需.规定要检查的事件.这个 e ...

  10. 智能指针之shared_ptr基本概述

    1.shared_ptr允许有多个指针指向同一个对象,unique_ptr独占所指向的对象. 2.类似于vector,智能指针也是模板.创建智能指针: shared_ptr<string> ...