Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save sachanganesh/b83650694453bb19611c1b5d3dfa4cc5 to your computer and use it in GitHub Desktop.
python-ported mutable preorder traversal in rust (tree_iter)
pub struct PreorderIter<'a> {
stack: Vec<&'a mut TreeNode>
}
impl<'a> PreorderIter<'a> {
pub fn new(root: Option<&'a mut TreeNode>) -> Self {
if let Some(node) = root {
PreorderIter {
stack: vec![node]
}
} else {
PreorderIter {
stack: vec![]
}
}
}
}
impl<'a> Iterator for PreorderIter<'a> {
type Item = &'a mut TreeNode;
fn next(&mut self) -> Option<Self::Item> {
if let Some(node) = self.stack.pop() {
if let Some(right) = &mut node.right {
self.stack.push(right)
}
if let Some(left) = &mut 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