Construct Binary Tree from Preorder and Postorder Traversal
Description
Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
Output: [1,2,3,4,5,6,7]Solutions
Intuitive recursive solution
class Solution {
public:
TreeNode *constructFromPrePost(vector<int> &pre, vector<int> &post) {
int n = pre.size();
vector<int> hash(n + 1);
for (int i = 0; i < n; ++i)
hash[post[i]] = i; // post is a permutation of [1,2,...,n]
return helper(pre, 0, n - 1, post, 0, n - 1, hash);
}
// build a binary tree from pre[l1..r1] and post[l2..r2]
TreeNode *helper(vector<int> &pre, int l1, int r1,
vector<int> &post, int l2, int r2,
vector<int> &hash) {
if (l1 > r1)
return nullptr;
auto root = new TreeNode(pre[l1]);
if (l1 == r1)
return root;
int lrv = pre[l1 + 1]; // left root val
int lri = hash[lrv]; // index of lrv in post
int nl = lri - l2 + 1; // number of nodes in left sub-tree
root->left = helper(pre, l1 + 1, l1 + nl,
post, l2, lri,
hash);
root->right = helper(pre, l1 + nl + 1, r1,
post, lri + 1, r2 - 1,
hash);
return root;
}
};Another recursive solution
Iterative solutions
Last updated