20240226 Finished

This commit is contained in:
jackfiled 2024-02-26 09:16:06 +08:00
parent 5ddfa86ac8
commit d251733113
2 changed files with 81 additions and 1 deletions

View File

@ -55,3 +55,4 @@ mod p106_construct_binary_tree_from_inorder_and_postorder_traversal;
mod p235_lowest_common_ancestor_of_a_binary_search_tree; mod p235_lowest_common_ancestor_of_a_binary_search_tree;
mod p2583_kth_largest_sum_in_a_binary_tree; mod p2583_kth_largest_sum_in_a_binary_tree;
mod p2476_closest_nodes_queries_in_a_binary_search_tree; mod p2476_closest_nodes_queries_in_a_binary_search_tree;
mod p938_range_sum_of_bst;

View File

@ -0,0 +1,79 @@
/**
* [938] Range Sum of BST
*/
pub struct Solution {}
use crate::util::tree::{TreeNode, to_tree};
// submission codes start here
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::VecDeque;
impl Solution {
pub fn range_sum_bst(root: Option<Rc<RefCell<TreeNode>>>, low: i32, high: i32) -> i32 {
let root = if let Some(r) = root {
r
} else {
return 0;
};
let mut sum = 0;
let mut deque = VecDeque::new();
deque.push_back(root);
while !deque.is_empty() {
let node = deque.pop_front().unwrap();
if node.borrow().val >= low && node.borrow().val <= high {
sum += node.borrow().val;
}
if node.borrow().val > low {
if let Some(left) = &node.borrow().left {
deque.push_back(Rc::clone(left));
}
}
if node.borrow().val < high {
if let Some(right) = &node.borrow().right {
deque.push_back(Rc::clone(right));
}
}
}
sum
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_938() {
assert_eq!(Solution::range_sum_bst(
to_tree(vec![Some(10), Some(5), Some(15), Some(3), Some(7), None, Some(18)]), 7, 15), 32);
}
}