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 range [1, 2 * 104].
1 <= Node.val <= 105
1 <= low <= high <= 105
All Node.val are unique.

把BST中在[low, high]范围内的节点求和

思路:
669题类似,669是把范围外的修剪掉。

BST的特征是左子树节点值 < root值 < 右子树节点值
可用中序遍历实现,中序遍历是升序排列的,所以中间满足条件的节点值直接相加即可。

class Solution {
    int res = 0;
    public int rangeSumBST(TreeNode root, int low, int high) {
        inOrder(root, low, high);
        return res;
    }

    void inOrder(TreeNode root, int low, int high) {
        if(root == null) return;
        inOrder(root.left, low, high);
        if(root.val >= low && root.val <= high) res += root.val;
        inOrder(root.right, low, high);
    }
}

如果root.val < low的话,那么整个左子树和root都pass,只需要返回对右子树求和的结果。同理root.val > high时,整个右子树和root都不考虑,只要返回对左子树求和的结果。
如果root.val在范围内,那把root.val加到结果,然后继续对它的左子树和右子树求和。
节点是null时返回null。
递归实现

public int rangeSumBST(TreeNode root, int low, int high) {
    if(root == null) return 0;
   
    if(root.val >= low && root.val <= high) {
        return root.val + rangeSumBST(root.left, low, high) + rangeSumBST(root.right, low, high);
    } else if(root.val < low) {
        return rangeSumBST(root.right, low, high);
    } 
    
    return rangeSumBST(root.left, low, high);
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值