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.
⏰ Time complexity: O(n^2), as we recursively divide the arrays
Locating the boundary of the left subtree requires O(n) to find an element in postorder (in the worst case for each call).
There are n recursive calls as we divide the arrays.
Overall time complexity is O(n^2) in the worst case due to the linear search.
🧺 Space complexity: O(n)
Recursion uses space O(h), where h is the height of the tree, due to recursion depth, which is proportional to the height of the tree. Which is O(n) in the worst case (skewed tree).
To speed up previous method, we can use the hashmap to store the indices of values from postorder.This way, we quickly locate the left subtree’s root (based on the second element in preorder) in (O(1)) time.
classSolution {
private HashMap<Integer, Integer> postIndexMap;
public TreeNode constructFromPrePost(int[] preorder, int[] postorder) {
// Build a HashMap for quick index lookup in postorder postIndexMap =new HashMap<>();
for (int i = 0; i < postorder.length; i++) {
postIndexMap.put(postorder[i], i);
}
return build(preorder, 0, preorder.length- 1, postorder, 0, postorder.length- 1);
}
private TreeNode build(int[] pre, int preStart, int preEnd, int[] post, int postStart, int postEnd) {
if (preStart > preEnd || postStart > postEnd) {
returnnull;
}
TreeNode root =new TreeNode(pre[preStart]); // Root is the first element in preorderif (preStart == preEnd) {
return root; // Single-node tree }
// Find left subtree boundary using the pre[preStart + 1] value in postorderint leftRootVal = pre[preStart + 1];
int idx = postIndexMap.get(leftRootVal);
// Calculate sizes of left and right subtreesint leftSize = idx - postStart + 1;
// Recursively build left and right subtrees root.left= build(pre, preStart + 1, preStart + leftSize, post, postStart, idx);
root.right= build(pre, preStart + leftSize + 1, preEnd, post, idx + 1, postEnd - 1);
return root;
}
}