#889
Medium Algorithms Construct binary tree from preorder and postorder traversal
Array Hash Table Divide and Conquer Tree Binary Tree
78.1% acceptance
Feb 27, 2026
3386
159
Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree.
If there exist multiple answers, you can return any of them.
Solution
Rust
Time O(2^n)
Space O(n)
/*
* Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree.
* If there exist multiple answers, you can return any of them.
* Example 1:
* Input: preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1]
* Output: [1,2,3,4,5,6,7]
* Example 2:
* Input: preorder = [1], postorder = [1]
* Output: [1]
* Constraints:
* 1 <= preorder.length <= 30
* 1 <= preorder[i] <= preorder.length
* All the values of preorder are unique.
* postorder.length == preorder.length
* 1 <= postorder[i] <= postorder.length
* All the values of postorder are unique.
* It is guaranteed that preorder and postorder are the preorder traversal and postorder traversal of the same binary tree.
*/
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn construct_from_pre_post(preorder: Vec<i32>, postorder: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
fn build(pre: &[i32], post: &[i32]) -> Option<Rc<RefCell<TreeNode>>> {
if pre.is_empty() { return None; }
let root = Rc::new(RefCell::new(TreeNode::new(pre[0])));
if pre.len() == 1 { return Some(root); }
let l_val = pre[1];
let l_size = post.iter().position(|&x| x == l_val).unwrap() + 1;
root.borrow_mut().left = build(&pre[1..1+l_size], &post[..l_size]);
root.borrow_mut().right = build(&pre[1+l_size..], &post[l_size..post.len()-1]);
Some(root)
}
build(&preorder, &postorder)
}
}