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

This commit is contained in:
fw_qaq
2022-11-23 01:57:45 -05:00
committed by GitHub
parent 3762f1a3e3
commit 183a62a923

View File

@ -1141,22 +1141,19 @@ object Solution {
106 从中序与后序遍历序列构造二叉树
```rust
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn build_tree(
mut inorder: Vec<i32>,
mut postorder: Vec<i32>,
) -> Option<Rc<RefCell<TreeNode>>> {
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.splice(0..index, []).collect(),
postorder.splice(0..index, []).collect(),
);
root.right = Self::build_tree(inorder.split_off(1), postorder);
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)))
}
}
@ -1168,21 +1165,18 @@ impl Solution {
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>>> {
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.splice(1..index + 1, []).collect(),
inorder.splice(0..index, []).collect(),
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(),
);
root.right = Self::build_tree(preorder.split_off(1), inorder.split_off(1));
Some(Rc::new(RefCell::new(root)))
}
}