Created
June 2, 2020 17:45
-
-
Save sachanganesh/ef855b0ff67326dbb1f5af2de0f37931 to your computer and use it in GitHub Desktop.
python-ported immutable 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 { | |
| stack: Vec<&TreeNode> | |
| } | |
| impl PreorderIter { | |
| pub fn new(root: Option<&TreeNode>) -> Self { | |
| if let Some(node) = root { | |
| PreorderIter { | |
| stack: vec![node] | |
| } | |
| } else { | |
| PreorderIter { | |
| stack: vec![] | |
| } | |
| } | |
| } | |
| } | |
| impl Iterator for PreorderIter { | |
| type Item = &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