Skip to content

Commit fbb5db0

Browse files
committed
Added solution of problem 173
1 parent d520842 commit fbb5db0

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed

src/solutions/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ pub mod s0164_maximum_gap;
9595
pub mod s0165_compare_version_numbers;
9696
pub mod s0167_two_sum_ii_input_array_is_sorted;
9797
pub mod s0172_factorial_trailing_zeroes;
98+
pub mod s0173_binary_search_tree_iterator;
9899
pub mod s0231_power_of_two;
99100
pub mod s0232_implement_queue_using_stacks;
100101
pub mod s0234_palindrome_linked_list;
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
use std::cell::RefCell;
2+
use std::rc::Rc;
3+
4+
#[derive(Debug, PartialEq, Eq)]
5+
pub struct TreeNode {
6+
pub val: i32,
7+
pub left: Option<Rc<RefCell<TreeNode>>>,
8+
pub right: Option<Rc<RefCell<TreeNode>>>,
9+
}
10+
11+
impl TreeNode {
12+
#[inline]
13+
pub fn new(val: i32) -> Self {
14+
TreeNode {
15+
val,
16+
left: None,
17+
right: None,
18+
}
19+
}
20+
}
21+
22+
pub struct BSTIterator {
23+
stack: Vec<Rc<RefCell<TreeNode>>>,
24+
}
25+
26+
impl BSTIterator {
27+
pub fn new(root: Option<Rc<RefCell<TreeNode>>>) -> Self {
28+
let mut iter = BSTIterator { stack: Vec::new() };
29+
iter.push_left(root);
30+
iter
31+
}
32+
33+
pub fn next(&mut self) -> i32 {
34+
let node = self.stack.pop().unwrap();
35+
36+
let val = node.borrow().val;
37+
if let Some(right) = node.borrow().right.clone() {
38+
self.push_left(Some(right));
39+
}
40+
41+
val
42+
}
43+
44+
pub fn has_next(&self) -> bool {
45+
!self.stack.is_empty()
46+
}
47+
48+
pub fn push_left(&mut self, mut node: Option<Rc<RefCell<TreeNode>>>) {
49+
while let Some(n) = node {
50+
self.stack.push(n.clone());
51+
node = n.borrow().left.clone();
52+
}
53+
}
54+
}
55+
56+
#[cfg(test)]
57+
mod test {
58+
use super::*;
59+
60+
#[test]
61+
fn test_case_1() {
62+
let mut bst_iterator: BSTIterator =
63+
BSTIterator::new(Some(Rc::new(RefCell::new(TreeNode {
64+
val: 7,
65+
left: Some(Rc::new(RefCell::new(TreeNode::new(3)))),
66+
right: Some(Rc::new(RefCell::new(TreeNode {
67+
val: 15,
68+
left: Some(Rc::new(RefCell::new(TreeNode::new(9)))),
69+
right: Some(Rc::new(RefCell::new(TreeNode::new(20)))),
70+
}))),
71+
}))));
72+
73+
assert_eq!(bst_iterator.next(), 3);
74+
assert_eq!(bst_iterator.next(), 7);
75+
assert_eq!(bst_iterator.has_next(), true);
76+
assert_eq!(bst_iterator.next(), 9);
77+
assert_eq!(bst_iterator.has_next(), true);
78+
assert_eq!(bst_iterator.next(), 15);
79+
assert_eq!(bst_iterator.has_next(), true);
80+
assert_eq!(bst_iterator.next(), 20);
81+
assert_eq!(bst_iterator.has_next(), false);
82+
}
83+
}

0 commit comments

Comments
 (0)