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

Example 2:

Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
Output: 23

 

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.

Rust Solution

struct Solution;
use rustgym_util::*;

trait Preorder {
    fn preorder(&self, l: i32, r: i32, sum: &mut i32);
}

impl Preorder for TreeLink {
    fn preorder(&self, l: i32, r: i32, sum: &mut i32) {
        if let Some(node) = self {
            let node = node.borrow();
            let left = &node.left;
            let right = &node.right;
            let val = node.val;
            if val >= l && val <= r {
                *sum += val;
            }
            if val > l {
                left.preorder(l, r, sum)
            }
            if val < r {
                right.preorder(l, r, sum);
            }
        }
    }
}

impl Solution {
    fn range_sum_bst(root: TreeLink, l: i32, r: i32) -> i32 {
        let mut sum = 0;
        root.preorder(l, r, &mut sum);
        sum
    }
}

#[test]
fn test() {
    let root = tree!(10, tree!(5, tree!(3), tree!(7)), tree!(15, None, tree!(18)));
    assert_eq!(Solution::range_sum_bst(root, 7, 15), 32);
}

Having problems with this solution? Click here to submit an issue on github.