forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.rs
62 lines (58 loc) · 1.47 KB
/
Solution.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
// 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
// }
// }
// }
struct BSTIterator {
vals: Vec<i32>,
index: usize,
}
use std::rc::Rc;
use std::cell::RefCell;
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl BSTIterator {
fn inorder(root: &Option<Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
if let Some(node) = root {
let node = node.as_ref().borrow();
Self::inorder(&node.left, res);
res.push(node.val);
Self::inorder(&node.right, res);
}
}
fn new(root: Option<Rc<RefCell<TreeNode>>>) -> Self {
let mut vals = vec![];
Self::inorder(&root, &mut vals);
BSTIterator {
vals,
index: 0,
}
}
fn next(&mut self) -> i32 {
self.index += 1;
self.vals[self.index - 1]
}
fn has_next(&self) -> bool {
self.index != self.vals.len()
}
}/**
* 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();
*/