Full Binary Tree using its Preorder and Mirror's Preorder
Last Updated : 27 May, 2026
Given two arrays pre[] and preMirror[] of size n containing unique elements, where pre[] represents the preorder traversal of a full binary tree and preMirror[] represents the preorder traversal of its mirror tree, construct the original full binary tree using these traversals.
Note: A general binary tree cannot be uniquely constructed using these two traversals. However, a full binary tree can be constructed uniquely from the given traversals without any ambiguity.
Examples:
Input: pre[] = {0,1,2}, preMirror[] = {0,2,1} Output: {0, 1, 2} Explanation: The tree will look like
[Naive Approach] Linear Search in Mirror Preorder ā O(n²) Time and O(n) Space
We use pre[] to pick nodes in root order, and preMirror[] to determine how the tree is split into left and right subtrees.
Take the first element of pre[] as the root.
Maintain a variable preIndex to track the current position in pre[].
For the next element in pre[], find its position in preMirror[]. This position divides the current range into left subtree range and right subtree range. In the above example pre[] = {1, 2, 4, 5, 3, 6, 7}, preMirror[] = {1, 3, 7, 6, 2, 5, 4}. Using the position of 2 in preMirror[], we can find left and right subtrees.
Recursively construct the left subtree using the right part of the split range and the right subtree using the left part of the split range.
Output
4 2 5 1 6 3 7
[Expected Approach] Hash Map or Dictionary Optimization ā O(n) Time and O(n) Space
To optimize the above solution, we store the index of every element of preMirror[] in a Hash Map so that we can find the split position in O(1) time. This helps us quickly divide the current range into left and right subtrees and build the tree efficiently using recursion.
Store all elements of preMirror[] in a Hash Map with their indices for fast lookup.
Take the first element of pre[] as the root and maintain a pointer preIndex.
For the next element in pre[], use the Hash Map to directly find its index in preMirror[].
This index divides the current range into left subtree range and right subtree range.
Recursively construct the left subtree and right subtree using the same logic.