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