20240612 Finished

This commit is contained in:
jackfiled 2024-06-12 14:43:30 +08:00
parent fc600cbb12
commit 43a9d62118
2 changed files with 119 additions and 1 deletions

View File

@ -147,3 +147,4 @@ mod p114_flatten_binary_tree_to_linked_list;
mod p112_path_sum; mod p112_path_sum;
mod p129_sum_root_to_leaf_numbers; mod p129_sum_root_to_leaf_numbers;
mod p124_binary_tree_maximum_path_sum; mod p124_binary_tree_maximum_path_sum;
mod p173_binary_search_tree_iterator;

View File

@ -0,0 +1,117 @@
/**
* [173] Binary Search Tree Iterator
*/
pub struct Solution {}
use tokio::time::error::Elapsed;
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;
struct BSTIterator {
stack: Vec<Rc<RefCell<TreeNode>>>
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl BSTIterator {
fn new(root: Option<Rc<RefCell<TreeNode>>>) -> Self {
if root.is_none() {
return BSTIterator {
stack: vec![]
};
}
let mut stack = vec![];
let root = root.unwrap();
let mut node = root;
loop {
stack.push(Rc::clone(&node));
let left = if let Some(left) = &node.borrow().left {
Rc::clone(left)
} else {
break;
};
node = left;
}
BSTIterator {
stack
}
}
fn next(&mut self) -> i32 {
let node = self.stack.pop().unwrap();
let val = node.borrow().val;
if let Some(right) = &node.borrow().right {
let mut node = Rc::clone(right);
loop {
self.stack.push(Rc::clone(&node));
let left = if let Some(left) = &node.borrow().left {
Rc::clone(left)
} else {
break;
};
node = left;
}
}
val
}
fn has_next(&self) -> bool {
!self.stack.is_empty()
}
}
/**
* Your BSTIterator object will be instantiated and called as such:
* let obj = BSTIterator::new(root);
* let ret_1: i32 = obj.next();
* let ret_2: bool = obj.has_next();
*/
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_173() {
}
}