Problem Description
Given the inorder and postorder traversal arrays of a binary tree (with unique node values), construct and return the binary tree.
Key Insights
- The last element of the postorder array is always the root.
- Finding the index of the root in the inorder array splits the tree into left and right subtrees.
- Recursively reconstruct the tree using the divided inorder arrays and corresponding segments of the postorder array.
- Use a hash table (or dictionary) to quickly locate the index of any value in the inorder array.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(n) (Space is used for the recursive call stack and extra hash table)
Solution
We can solve the problem by leveraging the observation that in postorder traversal, the last element is the root of the current subtree. After identifying the root, we locate its index in the inorder array which partitions the array into left and right subtrees. A hash table is used for fast lookup of the root index in the inorder sequence. We then recursively apply the same process for left and right subtrees, carefully managing indices to maintain alignment between the inorder and postorder arrays.