update 二叉树的迭代遍历.md about rust

This commit is contained in:
fw_qaq
2022-11-07 00:08:02 +08:00
committed by GitHub
parent 4df81ae0bb
commit 4ecf4714c7

View File

@ -640,6 +640,60 @@ object Solution {
}
}
```
rust:
```rust
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
//前序
pub fn preorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut res = vec![];
let mut stack = vec![root];
while !stack.is_empty() {
if let Some(node) = stack.pop().unwrap() {
res.push(node.borrow().val);
stack.push(node.borrow().right.clone());
stack.push(node.borrow().left.clone());
}
}
res
}
//中序
pub fn inorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut res = vec![];
let mut stack = vec![];
let mut node = root;
while !stack.is_empty() || node.is_some() {
while let Some(n) = node {
node = n.borrow().left.clone();
stack.push(n);
}
if let Some(n) = stack.pop() {
res.push(n.borrow().val);
node = n.borrow().right.clone();
}
}
res
}
//后序
pub fn postorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut res = vec![];
let mut stack = vec![root];
while !stack.is_empty() {
if let Some(node) = stack.pop().unwrap() {
res.push(node.borrow().val);
stack.push(node.borrow().left.clone());
stack.push(node.borrow().right.clone());
}
}
res.into_iter().rev().collect()
}
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>