938. 二叉搜索树的范围和

本文介绍了一种算法,用于计算二叉搜索树中指定范围内的节点值总和,通过优化递归过程提高效率。

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

提示:

树中的结点数量最多为10000个。
最终的答案保证小于2^31。

思路

我在这里先定义一个范围变量range,在range里面的都是题目要求的加数。

基本情况:L和R(代表的值,不是指题目中的变量L和R)在range里面
构造器:大于等于L,并且小于等于R的数在range里面

第一次实现

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int res = 0;

    public int rangeSumBST(TreeNode root, int L, int R) {
        if(root == null) {
            return 0;
        }

        if(root.val >= L && root.val <= R) {
            res = res + root.val;
        }

        rangeSumBST(root.left, L, R);
        rangeSumBST(root.right, L, R);

        return res;
    }
}

存在的问题:

  1. 因为直接递归调用自身,把不需要递归的节点都拿去递归了。如果当前节点都小于L了,那么这个节点的左子树的所有节点都小于L,是不符合条件的;如果当前节点已经大于R了,那么这个节点的右子树的节点都大于R,也是不符合条件的节点。这些节点都不需要遍历。
  2. 上面的实现是自身递归调用,每次都返回一个值,没有必要,只需要在最后一次返回就可以了。

更好的实现

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int res = 0;

    public int rangeSumBST(TreeNode root, int L, int R) {
        helper(root, L, R);
        return res;
    }

    public void helper(TreeNode root, int L, int R) {
        if(root != null) {
            if(root.val >= L && root.val <= R) {
                res = res + root.val;
            }

            if(root.val >= L) {
                rangeSumBST(root.left, L, R);
            }
            if(root.val <= R) {
                rangeSumBST(root.right, L, R);
            }
        }
    }
}
  • 时间复杂度:O(n)
  • 空间复杂度:O(h),h是树的高度
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值