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

This commit is contained in:
fw_qaq
2022-11-22 00:18:08 +08:00
committed by GitHub
parent f071df11f8
commit 3762f1a3e3

View File

@ -1138,6 +1138,30 @@ object Solution {
## rust ## rust
106 从中序与后序遍历序列构造二叉树
```rust
impl Solution {
pub fn build_tree(
mut inorder: Vec<i32>,
mut postorder: Vec<i32>,
) -> Option<Rc<RefCell<TreeNode>>> {
if inorder.is_empty() {
return None;
}
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.splice(0..index, []).collect(),
postorder.splice(0..index, []).collect(),
);
root.right = Self::build_tree(inorder.split_off(1), postorder);
Some(Rc::new(RefCell::new(root)))
}
}
```
105 从前序与中序遍历序列构造二叉树 105 从前序与中序遍历序列构造二叉树
```rust ```rust