Update 0106.从中序与后序遍历序列构造二叉树.md

This commit is contained in:
fw_qaq
2022-11-22 00:01:41 +08:00
committed by GitHub
parent b7d29cbe04
commit f071df11f8

View File

@ -1136,6 +1136,34 @@ object Solution {
} }
``` ```
## rust
105 从前序与中序遍历序列构造二叉树
```rust
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn build_tree(
mut preorder: Vec<i32>,
mut 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.splice(1..index + 1, []).collect(),
inorder.splice(0..index, []).collect(),
);
root.right = Self::build_tree(preorder.split_off(1), inorder.split_off(1));
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"/>