给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和。
示例
示例 1:
输入:root = [10,5,15,3,7,null,18], low = 7, high = 15
输出:32
示例 2:
输入:root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
输出:23
题解
遍历二叉树,判断节点的值是否落在区间中,累加。这里可以根据搜索二叉树的性质,左子节点的值小于该节点的值,右子节点的值大于该节点的值。所以当节点的值小于 low 时,就不用遍历该节点的左子节点,但值大于 high 时也不需要遍历该节点的右子节点
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} low
* @param {number} high
* @return {number}
*/
var rangeSumBST = function(root, low, high) {
let sum = 0
const run = node => {
if (node.val >= low && node.val <= high) {
sum += node.val
}
if (node.left && node.val > low) {
run(node.left)
}
if (node.right && node.val < high) {
run(node.right)
}
}
run(root)
return sum
};
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/range-sum-of-bst
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。