@@ -149,13 +149,78 @@ pub fn lowest_common_ancestor(
149149 }
150150 None
151151}
152+
153+ /// [938. 二叉搜索树的范围和](https://leetcode.cn/problems/range-sum-of-bst/)
154+ pub fn range_sum_bst ( root : Option < Rc < RefCell < TreeNode > > > , low : i32 , high : i32 ) -> i32 {
155+ fn inorder ( node : Option < Rc < RefCell < TreeNode > > > , store : & mut Vec < i32 > ) {
156+ if node. is_none ( ) {
157+ return ;
158+ }
159+ let inner = node. unwrap ( ) . clone ( ) ;
160+ inorder ( inner. borrow ( ) . left . clone ( ) , store) ;
161+ store. push ( inner. borrow ( ) . val ) ;
162+ inorder ( inner. borrow ( ) . right . clone ( ) , store) ;
163+ }
164+ let mut store = vec ! [ ] ;
165+ inorder ( root, & mut store) ;
166+
167+ let left = match store. binary_search ( & low) {
168+ Ok ( idx) => idx,
169+ Err ( idx) => idx,
170+ } ;
171+ let right = match store. binary_search ( & high) {
172+ Ok ( idx) => idx+1 ,
173+ Err ( idx) => idx,
174+ } ;
175+ //println!("left: {}, right: {}, store {:?}", left, right, &store[left..right]);
176+
177+ store[ left..right] . iter ( ) . sum ( )
178+ }
179+
152180#[ cfg( test) ]
153181mod tests {
154182 use crate :: vec2;
155183
156184 use super :: * ;
157185 use macros:: tree;
158186
187+ #[ test]
188+ fn test_range_sum_bst ( ) {
189+ struct Testcase {
190+ tree : Option < Rc < RefCell < TreeNode > > > ,
191+ low : i32 ,
192+ high : i32 ,
193+ expect : i32 ,
194+ }
195+
196+ vec ! [
197+ Testcase {
198+ tree: tree!( { 10 , left: { 5 , left: { 3 } , right: { 7 } } , right: { 15 , right: { 18 } } } ) ,
199+ low: 7 ,
200+ high: 15 ,
201+ expect: 32 ,
202+ } ,
203+ Testcase {
204+ tree: tree!{ val: 10 , left: { val: 5 , left: { val: 3 , left: { val: 1 } } , right: { val: 7 , left: { val: 6 } } } , right: { val: 15 , left: { val: 13 } , right: { val: 18 } } } ,
205+ low: 6 ,
206+ high: 10 ,
207+ expect: 23 ,
208+ } ,
209+ ]
210+ . into_iter ( )
211+ . enumerate ( )
212+ . for_each ( |( idx, testcase) | {
213+ let Testcase {
214+ tree,
215+ low,
216+ high,
217+ expect,
218+ } = testcase;
219+ let acutal = range_sum_bst ( tree, low, high) ;
220+ assert_eq ! ( expect, acutal, "case {} failed" , idx) ;
221+ } ) ;
222+ }
223+
159224 #[ test]
160225 fn test_lowest_common_ancestor ( ) {
161226 struct Testcase {
0 commit comments