[Naive Recursive] Searching Root in Inorder - O(n²) Time and O(n) Space
The idea is based on the properties of preorder and inorder traversals. In preorder traversal, the first element is always the root of the current subtree. By searching this root in the inorder traversal, the left and right subtrees can be identified.
Take the first element of the current preorder range as the root
Find the root's index in the inorder traversal using linear search
Recursively process the left and right subtrees
Append the root to the postorder traversal
Output
4 5 2 6 3 1
[Efficient Approach] Hash Map for Inorder Lookup - O(n) Time and O(n) Space
The idea is to avoid repeatedly searching for the root in the inorder traversal. A hash map is used to store the index of every node in the inorder traversal.
Store each inorder value and its index in a hash map
Maintain a preorder index pointing to the current root
For each recursive call: Take the current preorder element as the root and find its inorder position using the hash map