mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Update 0106.从中序与后序遍历序列构造二叉树.md
This commit is contained in:
@ -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">
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
|
Reference in New Issue
Block a user