mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
Merge pull request #1771 from fwqaaq/master
Update 0106.从中序与后序遍历序列构造二叉树.md about rust
This commit is contained in:
@ -1149,6 +1149,52 @@ object Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## rust
|
||||||
|
|
||||||
|
106 从中序与后序遍历序列构造二叉树
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use std::cell::RefCell;
|
||||||
|
use std::rc::Rc;
|
||||||
|
impl Solution {
|
||||||
|
pub fn build_tree(inorder: Vec<i32>, postorder: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
|
||||||
|
if inorder.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut postorder = postorder;
|
||||||
|
let root = postorder.pop().unwrap();
|
||||||
|
let index = inorder.iter().position(|&x| x == root).unwrap();
|
||||||
|
let mut root = TreeNode::new(root);
|
||||||
|
root.left = Self::build_tree(inorder[..index].to_vec(), postorder[..index].to_vec());
|
||||||
|
root.right = Self::build_tree(inorder[index + 1..].to_vec(), postorder[index..].to_vec());
|
||||||
|
Some(Rc::new(RefCell::new(root)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
105 从前序与中序遍历序列构造二叉树
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use std::cell::RefCell;
|
||||||
|
use std::rc::Rc;
|
||||||
|
impl Solution {
|
||||||
|
pub fn build_tree(preorder: Vec<i32>, inorder: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
|
||||||
|
if preorder.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let root = preorder[0];
|
||||||
|
let index = inorder.iter().position(|&x| x == root).unwrap();
|
||||||
|
let mut root = TreeNode::new(root);
|
||||||
|
root.left = Self::build_tree(preorder[1..index + 1].to_vec(), inorder[0..index].to_vec());
|
||||||
|
root.right = Self::build_tree(
|
||||||
|
preorder[index + 1..].to_vec(),
|
||||||
|
inorder[index + 1..].to_vec(),
|
||||||
|
);
|
||||||
|
Some(Rc::new(RefCell::new(root)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||||
|
Reference in New Issue
Block a user