LeetCode.938-范围内求二叉搜索树节点值之和(Range Sum of BST)

SAP 财务BAPI_ACC_DOCUMENT_POST批导的税务tax 最近遇到了关于SAP财务凭证批导要bapi:BAPI_ACC_DOCUMENT_POST增加税的功能要求,查阅了一众文献发现都不尽如人意,所以想着自己写一个趟过的雷吧。 一般前台sap的凭证是有自动计算税码的勾选框的,但是bapi却并没有这个字段。 实际操作过程中1.可以定义一个税额的结构,参考bapiactx09 2.在会计分录上传如果需要增加税码的时候,譬如总账gl,需要对应tax_code 3.通过CALCULATE_TAX_FROM_GROSSAMOUNT 计算出税额和acct_k... 阅读详情

这是悦乐书的第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+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。

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

深入理解C语言内存管理:堆与栈的区别 栈是一种遵循后进先出(LIFO)原则的数据结构。在程序中,栈用于存储局部变量、函数的参数以及函数调用时的返回地址等信息。栈的内存管理由操作系统自动进行,每次函数调用时都会在栈上分配一块内存区域,函数执行完毕后,该内存区域会自动释放。在C语言中,堆与栈是两种不同的内存分配方式,各自有着不同的特点和适用场景。栈内存自动管理,访问速度快,但大小有限,适用于存储局部变量和函数调用信息。堆内存由程序员手动管理,适用于存储动态数据结构,大小不受限制,但访问速度较慢,容易导致内存泄漏等问题。 阅读详情

相关推荐

避坑指南:LISFLOOD-FP模型数据单位、参数文件与results文件夹结果解析全攻略

本文详细解析了LISFLOOD-FP洪水模拟模型的关键应用环节,包括数据单位校验、参数文件优化及结果文件解读与可视化。特别针对常见的单位混淆问题,提供了从DEM到边界条件的全面校验方法,并深入剖析了.par参数文件的配置技巧,帮助用户避免模型崩溃和结果失真。

weixin_42533622的博客 246

LeetCode,二叉树,二叉搜索树

leetcode。二叉搜索树

qq_45031079的博客 217

[kriging](一)网上下载的kriging克里金的C++程序的初步调试

笔者在网上下载了一份克里金的C++程序,水平有限,正在逐步地调试中。 初步 克里金法现在在许多软件都已经有集成了,据笔者所知: arcgis : 看过有的arcgis培训视频里面简略介绍了里面的插值方法,有克里金。 surfer :笔者用过这个,效果很好。 gocad :听说有 landmark &jason :研究生时候用的专业的石油物探软件,里面有克里金法,万恶的开始。 pykrig...

FORESTCSDN 5623

BST中所有结点之和(设结点个数为n,且中序遍历为等差数列)

其实,就是要求最小值和最大值之和, 程序如下: #include using namespace std; // BST的结点 typedef struct node { int key; struct node *lChild, *rChild; }Node, *BST; // 在给定的BST插入element, 使之称为新的BST bool BSTInsert(Node * &

认知 行动 坚持 8227

Qt+WebAssembly学习笔记(六)win10+Qt6.4.0rc1开发环境搭建

前言:因项目的缘故,笔者有段时间没测试了,官方也修复了很问题,笔者今天记录下最新版本环境搭建。

aggs1990的专栏 3781

Vivado加上VsCode让你的生活更美好

VsCode与Vivado的灵活使用 引言 ​ 现在大二了,在接触硬件描述语言。Vivado自带的编辑器实在很难用,为了能够“极客”一些,当然是去Google了一下有哪些方法可以取而代之。 ​ 网络上的答案大同小异,基本上都是用的Sublime Text.(我的学长们也几乎都是) 平时码代码的过程中,我习惯与使用VsCode,尤其是在微软收购GitHub之后,Code 简直就是神器了。于是乎…一个...

qq_39498701的博客 10万+

leetcode----给定一个二叉树和一个值 sum,请找出所有的根节点到叶子节点的节点值之和等于sum 的路径,

import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * } */ public class Solution { /** * * @param root TreeNode类 * @param sum int整型 * @return int整型Ar...

sunnnnh的博客 1738

深入理解HTTPS:从SSLHandshakeException到证书链验证的完整解析

本文深入解析了HTTPS握手过程中常见的SSLHandshakeException异常,特别是由证书链验证失败引发的CertPathValidatorException。文章从TLS握手流程、证书链验证的数学原理出发,详细剖析了Java中TrustManager的工作机制,并提供了针对证书链不完整、自签名证书等典型问题的系统化排查流程与实战解决方案。

weixin_29313423的博客 243

938.二叉搜索树的范围和

题目 给定二叉搜索树的根结点 root,返回 L 和 R(含)之间的所有结点的值的和。 二叉搜索树保证具有唯一的值。 示例 1: 输入:root = [10,5,15,3,7,null,18], L = 7, R = 15 输出:32 示例 2: 输入:root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10 输出:23 分析 这道题要求的就是一棵树...

Lgnorant的博客 241

国内优秀MES开源框架

一套springboot 开源框架 代码标准规范化。 界面展示 演示地址 http://wangziyangmes.pzzd.xyz 用户名admin 密码123 系统管理 工艺管理 计划管理 物料管理 *用户管理* *工艺路线管理* 工单下达...

q707231019的博客 2万+

单片机:实现简单的时间片轮询调度(附完整源码)

单片机:实现简单的时间片轮询调度(附完整源码)

希望我的博客,能帮上你解决学习中工作中所遇到的问题 405

LeetCode //C - 938. Range Sum of BST

Summary: The problem requires summing the values of nodes within a given range [low, high] in a binary search tree (BST). The solution leverages the BST property to optimize traversal. If a node's value is below low, only the right subtree is explored (lef

Made in Code 627

Python 爬虫实战:拼多多商品评论情感分析(含词云生成与差评预警)

在电商行业竞争日益激烈的当下,商家对商品评论的分析需求愈发迫切。通过 Python 爬虫收集拼多多商品评论,并结合情感分析、词云可视化及差评预警技术,商家可精准洞察消费者反馈,优化商品与服务。本文将深度剖析从爬虫搭建到数据挖掘的关键环节,助力读者构建全流程电商评论分析系统。

yansideyucsdn的博客 1457

[Leetcode][Python][DFS] 938. Range Sum of BST

[Leetcode][Python][DFS] 938. Range Sum of BST题目大意题目解析代码 题目大意 给定root二叉搜索树的节点,返回范围为[low, high] 的所有节点的值之和。 例题: 输入: root = [10,5,15,3,7,null,18],low = 7,high = 15 输出: 7+10+15 = 32 题目解析 第一点:利用BTS性质,node.left.val < node.val < node.right.val 第二点:DFS 第三点:递归

TwinkleZhao的博客 230

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

LeetCode 938. Range Sum of BST

[Med] LeetCode 938. Range Sum of BST 链接: https://leetcode.com/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 ...

MrJustin的博客 238

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

938. Range Sum of BST*

938. Range Sum of BST* https://leetcode.com/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). T...

珍妮的选择的博客 293

InTheHand.Net.Personal+BlueTooth4,蓝牙开发

项目中有蓝牙开发的必备dll,现在网上相关的文档博客不少,有的说的多有的说少,但是却很少有这两个dll,分享一下。

[leetcode]938. Range Sum of BST(Python)

[leetcode]938. Range Sum of BST题目描述题目理解解题思路递归MyMethodTime 题目描述 Category:Easy Tree Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclus...

La_Ragazza的博客 370

leetcode 938. Range Sum of BST (BST某个范围内的和)

题目要求 给定一颗二叉搜索树,返回摸个范围内节点的和,包括L,R。其中BST中的值都是唯一的。 解题思路 对BST进行前序遍历,结果就是从小到大的顺序,所以,我们只要在遍历的时候,同时记录[L,R]范围内的数值和即可。 主要代码c++ class Solution { public: int sum = 0; int rangeSumBST(TreeNode* root, int...

爱喝舒化奶的博客 289

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

qq_39378221的博客 211

[LeetCode] 938. Range Sum of BST 二叉搜索树的区间和

Given the rootnode of a binary search tree, return the sum of values of all nodes with valu...

azl397985856的专栏 245

LeetCode 938. 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. 二、代码 /** *...

可控的事情要谨慎,不可控的事情要乐观。 212

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

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 Constraints: The number of nodes in the tree is in the

蓝羽飞鸟的博客 206

[LeetCode] 938. Range Sum of BST

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

dfojc86648的专栏 78

[leetcode] 938. Range Sum of BST @ python

原题 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: Inp...

闲庭信步 365

[leetcode] 938. Range Sum of BST

Description 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

Learning from the mistakes 205
上一篇: LeetCode.937-重新排序日志数组(Reorder Log Files)
下一篇: LeetCode.941-有效山形数组(Valid Mountain Array)
程序员小川
博客等级 码龄10年 47粉丝 305原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址