VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cartesian-tree-from-inorder-traversal-segment-tree/

⇱ Cartesian tree from inorder traversal | Segment Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Cartesian tree from inorder traversal | Segment Tree

Last Updated : 12 Jul, 2025

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}:  

  1. Find the maximum in this range {L, R} using range-max query on the segment-tree. Let's say 'M' is index the maximum in the range.
  2. Pick up 'arr[M]' as the value for current node and create a node with this value.
  3. Solve for range {L, M-1} and {M+1, R}.
  4. Set the node returned by {L, M-1} as the left child of current node and {M+1, R} as the right child.

Below is the implementation of the above approach:  


Output: 
8 11 21 100 5 70 55

 

Time complexity: O(N+logN)
Auxiliary Space: O(N).  

Related Topic: Segment Tree

Comment
Article Tags:
Article Tags: