diff --git a/problems/二叉树的统一迭代法.md b/problems/二叉树的统一迭代法.md index 030d3ae1..69c23e5c 100644 --- a/problems/二叉树的统一迭代法.md +++ b/problems/二叉树的统一迭代法.md @@ -666,6 +666,83 @@ object Solution { } } ``` + +rust: + +```rust +impl Solution{ + // 前序 + pub fn preorder_traversal(root: Option>>) -> Vec { + let mut res = vec![]; + let mut stack = vec![]; + if root.is_some(){ + stack.push(root); + } + while !stack.is_empty(){ + if let Some(node) = stack.pop().unwrap(){ + if node.borrow().right.is_some(){ + stack.push(node.borrow().right.clone()); + } + if node.borrow().left.is_some(){ + stack.push(node.borrow().left.clone()); + } + stack.push(Some(node)); + stack.push(None); + }else{ + res.push(stack.pop().unwrap().unwrap().borrow().val); + } + } + res + } + // 中序 + pub fn inorder_traversal(root: Option>>) -> Vec { + let mut res = vec![]; + let mut stack = vec![]; + if root.is_some() { + stack.push(root); + } + while !stack.is_empty() { + if let Some(node) = stack.pop().unwrap() { + if node.borrow().right.is_some() { + stack.push(node.borrow().right.clone()); + } + stack.push(Some(node.clone())); + stack.push(None); + if node.borrow().left.is_some() { + stack.push(node.borrow().left.clone()); + } + } else { + res.push(stack.pop().unwrap().unwrap().borrow().val); + } + } + res + } + // 后序 + pub fn postorder_traversal(root: Option>>) -> Vec { + let mut res = vec![]; + let mut stack = vec![]; + if root.is_some() { + stack.push(root); + } + while !stack.is_empty() { + if let Some(node) = stack.pop().unwrap() { + stack.push(Some(node.clone())); + stack.push(None); + if node.borrow().right.is_some() { + stack.push(node.borrow().right.clone()); + } + if node.borrow().left.is_some() { + stack.push(node.borrow().left.clone()); + } + } else { + res.push(stack.pop().unwrap().unwrap().borrow().val); + } + } + res + } +} +``` +