Created
June 2, 2020 17:49
-
-
Save sachanganesh/7dc7f08f517dd3ae5c179d1cfa58c6d9 to your computer and use it in GitHub Desktop.
python-ported immutable preorder traversal with lifetimes in rust (tree_iter)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| pub struct PreorderIter<'a> { // explicitly annotate the lifetime of the struct | |
| stack: Vec<&'a TreeNode> // specify that the borrow lives for as long as the struct lives | |
| } | |
| impl<'a> PreorderIter<'a> { // declare the lifetime and apply as lifetime of the struct | |
| pub fn new(root: Option<&'a TreeNode>) -> Self { // annotate lifetime of the borrow | |
| if let Some(node) = root { | |
| PreorderIter { | |
| stack: vec![node] | |
| } | |
| } else { | |
| PreorderIter { | |
| stack: vec![] | |
| } | |
| } | |
| } | |
| } | |
| impl<'a> Iterator for PreorderIter<'a> { | |
| type Item = &'a TreeNode; | |
| fn next(&mut self) -> Option<Self::Item> { | |
| if let Some(node) = self.stack.pop() { | |
| if let Some(right) = &node.right { | |
| self.stack.push(&right) | |
| } | |
| if let Some(left) = &node.left { | |
| self.stack.push(&left) | |
| } | |
| return Some(node) | |
| } | |
| return None | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment