From 43a9d62118a653bc1490488aeaf584c9221f9a4d Mon Sep 17 00:00:00 2001 From: jackfiled Date: Wed, 12 Jun 2024 14:43:30 +0800 Subject: [PATCH] 20240612 Finished --- src/problem/mod.rs | 3 +- .../p173_binary_search_tree_iterator.rs | 117 ++++++++++++++++++ 2 files changed, 119 insertions(+), 1 deletion(-) create mode 100644 src/problem/p173_binary_search_tree_iterator.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 8051d6d..bc02c4c 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -146,4 +146,5 @@ mod p101_symmetric_tree; mod p114_flatten_binary_tree_to_linked_list; mod p112_path_sum; mod p129_sum_root_to_leaf_numbers; -mod p124_binary_tree_maximum_path_sum; \ No newline at end of file +mod p124_binary_tree_maximum_path_sum; +mod p173_binary_search_tree_iterator; \ No newline at end of file diff --git a/src/problem/p173_binary_search_tree_iterator.rs b/src/problem/p173_binary_search_tree_iterator.rs new file mode 100644 index 0000000..a4428db --- /dev/null +++ b/src/problem/p173_binary_search_tree_iterator.rs @@ -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>>, +// pub right: Option>>, +// } +// +// 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>> +} + +/** + * `&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>>) -> 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() { + } +}