Skip to content

Instantly share code, notes, and snippets.

@sachanganesh
Created June 2, 2020 17:49
Show Gist options
  • Select an option

  • Save sachanganesh/7dc7f08f517dd3ae5c179d1cfa58c6d9 to your computer and use it in GitHub Desktop.

Select an option

Save sachanganesh/7dc7f08f517dd3ae5c179d1cfa58c6d9 to your computer and use it in GitHub Desktop.
python-ported immutable preorder traversal with lifetimes in rust (tree_iter)
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