Skip to content

Commit 1e40f29

Browse files
authored
update 二叉树的统一迭代法.md about rust
1 parent 4df81ae commit 1e40f29

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

problems/二叉树的统一迭代法.md

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -666,6 +666,83 @@ object Solution {
666666
}
667667
}
668668
```
669+
670+
rust:
671+
672+
```rust
673+
impl Solution{
674+
// 前序
675+
pub fn preorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
676+
let mut res = vec![];
677+
let mut stack = vec![];
678+
if root.is_some(){
679+
stack.push(root);
680+
}
681+
while !stack.is_empty(){
682+
if let Some(node) = stack.pop().unwrap(){
683+
if node.borrow().right.is_some(){
684+
stack.push(node.borrow().right.clone());
685+
}
686+
if node.borrow().left.is_some(){
687+
stack.push(node.borrow().left.clone());
688+
}
689+
stack.push(Some(node));
690+
stack.push(None);
691+
}else{
692+
res.push(stack.pop().unwrap().unwrap().borrow().val);
693+
}
694+
}
695+
res
696+
}
697+
// 中序
698+
pub fn inorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
699+
let mut res = vec![];
700+
let mut stack = vec![];
701+
if root.is_some() {
702+
stack.push(root);
703+
}
704+
while !stack.is_empty() {
705+
if let Some(node) = stack.pop().unwrap() {
706+
if node.borrow().right.is_some() {
707+
stack.push(node.borrow().right.clone());
708+
}
709+
stack.push(Some(node.clone()));
710+
stack.push(None);
711+
if node.borrow().left.is_some() {
712+
stack.push(node.borrow().left.clone());
713+
}
714+
} else {
715+
res.push(stack.pop().unwrap().unwrap().borrow().val);
716+
}
717+
}
718+
res
719+
}
720+
// 后序
721+
pub fn postorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
722+
let mut res = vec![];
723+
let mut stack = vec![];
724+
if root.is_some() {
725+
stack.push(root);
726+
}
727+
while !stack.is_empty() {
728+
if let Some(node) = stack.pop().unwrap() {
729+
stack.push(Some(node.clone()));
730+
stack.push(None);
731+
if node.borrow().right.is_some() {
732+
stack.push(node.borrow().right.clone());
733+
}
734+
if node.borrow().left.is_some() {
735+
stack.push(node.borrow().left.clone());
736+
}
737+
} else {
738+
res.push(stack.pop().unwrap().unwrap().borrow().val);
739+
}
740+
}
741+
res
742+
}
743+
}
744+
```
745+
669746
<p align="center">
670747
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
671748
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>

0 commit comments

Comments
 (0)