【Leetcode刷题篇】leetcode938 二叉搜索树的范围和
发布日期:2021-06-29 15:33:25 浏览次数:2 分类:技术文章

本文共 652 字,大约阅读时间需要 2 分钟。

题目:给定二叉搜索树的根结点 root,返回 L 和 R(含)之间的所有结点的值的和。

二叉搜索树保证具有唯一的值。

在这里插入图片描述
题解思路:对中序遍历的值进行处理即可

package com.lcz.leetcode;/** * 二叉搜索树的范围和 * @author LvChaoZhang * */public class Leetcode938 {
class TreeNode{
int val; TreeNode left; TreeNode right; TreeNode(int x){
val = x; } } private int sum = 0; public int rangeSumBST(TreeNode root,int L,int R) {
// 中序遍历来解决 return inorder(root,L,R); } private int inorder(TreeNode root,int L,int R) {
// 遍历截止条件 if(root==null) {
return 0; } // 左子树 inorder(root.left,L,R); // 对结点的处理 if(root.val>=L&&root.val<=R) {
sum += root.val; } // 右子树 inorder(root.right,L,R); return sum; } }

转载地址:https://codingchaozhang.blog.csdn.net/article/details/109492529 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:【Leetcode刷题篇】leetcode235 二叉搜索树的最近公共祖先
下一篇:【Leetcode刷题篇】leetcoe109 有序链表转换二叉搜索树

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年04月19日 20时58分56秒