-
Notifications
You must be signed in to change notification settings - Fork 1
/
173.binary-search-tree-iterator.rs
79 lines (66 loc) · 1.73 KB
/
173.binary-search-tree-iterator.rs
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
/*
* @lc app=leetcode id=173 lang=rust
*
* [173] Binary Search Tree Iterator
*/
// @lc code=start
// 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<Option<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(mut root: Option<Rc<RefCell<TreeNode>>>) -> Self {
let mut stack = vec![];
while let Some(node) = root.clone() {
stack.push(root.clone());
root = node.borrow().left.clone();
}
BSTIterator { stack }
}
/** @return the next smallest number */
fn next(&mut self) -> i32 {
let mut root = self.stack.pop().unwrap();
let node = root.unwrap();
let ans = node.borrow().val;
root = node.borrow().right.clone();
while let Some(node) = root.clone() {
self.stack.push(root.clone());
root = node.borrow().left.clone();
}
ans
}
/** @return whether we have a next smallest number */
fn has_next(&self) -> bool {
self.stack.len() > 0
}
}
/**
* 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();
*/
// @lc code=end