Created
June 2, 2020 17:55
-
-
Save sachanganesh/b83650694453bb19611c1b5d3dfa4cc5 to your computer and use it in GitHub Desktop.
python-ported mutable preorder traversal 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> { | |
| 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