Skip to content

Commit a8c62c7

Browse files
committed
8-15-2020
1 parent 8ffd93f commit a8c62c7

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

src/_0938_range_sum_of_bst.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
struct Solution;
2+
use crate::util::*;
3+
use std::cell::RefCell;
4+
use std::rc::Rc;
5+
6+
impl Solution {
7+
pub fn range_sum_bst(root: Option<Rc<RefCell<TreeNode>>>, l: i32, r: i32) -> i32 {
8+
let mut sum: i32 = 0;
9+
Self::traverse(&root, l, r, &mut sum);
10+
sum
11+
}
12+
13+
fn traverse(root: &Option<Rc<RefCell<TreeNode>>>, l: i32, r: i32, sum: &mut i32) {
14+
if let Some(node) = root {
15+
let h_value: i32 = node.borrow().val;
16+
if h_value >= l && h_value <= r {
17+
*sum += h_value;
18+
}
19+
Self::traverse(&node.borrow().left, l, r, sum);
20+
Self::traverse(&node.borrow().right, l, r, sum);
21+
}
22+
}
23+
}
24+
25+
#[test]
26+
fn test() {
27+
let root = tree!(10, tree!(5, tree!(3), tree!(7)), tree!(15, None, tree!(18)));
28+
assert_eq!(Solution::range_sum_bst(root, 7, 15), 32);
29+
}

src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,8 @@ mod _0922_sort_array_by_parity_ii;
190190
//
191191
mod _0937_reorder_data_in_log_files;
192192
//
193+
mod _0938_range_sum_of_bst;
194+
//
193195
mod _0953_verifying_an_alien_dictionary;
194196
//
195197
mod _0977_squares_of_a_sorted_array;

0 commit comments

Comments
 (0)