mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Merge pull request #1738 from Jack-Zhang-1314/patch-8
update 二叉树的迭代遍历.md about rust
This commit is contained in:
@ -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"/>
|
||||
|
Reference in New Issue
Block a user