-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathsearch_val_or_range_in_bst.rs
More file actions
36 lines (33 loc) · 1018 Bytes
/
search_val_or_range_in_bst.rs
File metadata and controls
36 lines (33 loc) · 1018 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
use super::prelude::*;
fn search_val_in_bst(
root: Option<Rc<RefCell<TreeNode>>>,
val: i32,
) -> Option<Rc<RefCell<TreeNode>>> {
let mut cur = root;
while let Some(node_outer) = cur {
let node = node_outer.borrow();
match node.val.cmp(&val) {
std::cmp::Ordering::Less => cur = node.right.clone(),
std::cmp::Ordering::Greater => cur = node.left.clone(),
std::cmp::Ordering::Equal => {
drop(node);
return Some(node_outer);
}
}
}
None
}
/// https://leetcode.com/problems/range-sum-of-bst/
fn range_sum_bst(root: Option<Rc<RefCell<TreeNode>>>, low: i32, high: i32) -> i32 {
let mut res = 0;
let mut stack = vec![root];
while let Some(Some(peek)) = stack.pop() {
let peek = peek.borrow();
if low <= peek.val && peek.val <= high {
res += peek.val;
}
stack.push(peek.right.clone());
stack.push(peek.left.clone());
}
res
}