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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| #![allow(unused)]
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
#[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, } } } struct BSTIterator { next: usize, vec: Vec<Rc<RefCell<TreeNode>>>, }
impl BSTIterator { fn new(root: Option<Rc<RefCell<TreeNode>>>) -> Self { let mut bst_iter = BSTIterator { next: 0, vec: Vec::new(), }; let mut stack = VecDeque::new();
let mut p = root; while p.is_some() || !stack.is_empty() { if let Some(node) = p { stack.push_back(node.clone()); p = node.borrow().left.clone(); } else { let node = stack.pop_back().unwrap(); bst_iter.vec.push(node.clone()); p = node.borrow().right.clone(); } } bst_iter }
fn next(&mut self) -> i32 { if let Some(node) = self.vec.get(self.next) { self.next += 1; node.borrow().val } else { i32::MIN } }
fn has_next(&self) -> bool { self.vec.len() > self.next } }
fn main() { }
|