![]() |
VOOZH | about |
Given an in-order traversal of a cartesian tree, the task is to build the entire tree from it.
Examples:
Input: arr[] = {1, 5, 3}
Output: 1 5 3
5
/ \
1 3
Input: arr[] = {3, 7, 4, 8}
Output: 3 7 4 8
8
/
7
/ \
3 4
Approach: We have already seen an algorithm here that takes O(NlogN) time on an average but can get to O(N2) in the worst case.
In this article, we will see how to build the cartesian in worst case running time of O(Nlog(N)). For this, we will use segment-tree to answer range-max queries.
Below will be our recursive algorithm on range {L, R}:
Below is the implementation of the above approach:
8 11 21 100 5 70 55
Time complexity: O(N+logN)
Auxiliary Space: O(N).
Related Topic: Segment Tree