Write an efficient algorithm to construct a Cartesian tree from inorder traversal. A Cartesian tree is a binary tree with the heap property: the parent of any node has a smaller value than the node itself.

For example, the following figure shows an example of a Cartesian tree derived from the sequence of numbers in inorder order:

 
Cartesian Tree

Practice this problem

Based on the heap property, the Cartesian tree root is the smallest number of the inorder sequence. The idea is to find the minimum element index in the inorder sequence and construct the root node from it. The left subtree consists of the values earlier than the root in the inorder sequence, while the right subtree consists of the values later than the root. Recursively follow this pattern for all nodes in the tree to construct the complete Cartesian tree.

Following is the implementation of the above algorithm in C++, Java, and Python:

C++


Download  Run Code

Output:

Inorder traversal of the constructed Cartesian tree is 9 3 7 1 8 12 10 20 15 18 5

Java


Download  Run Code

Output:

Inorder traversal of the constructed Cartesian tree is 9 3 7 1 8 12 10 20 15 18 5

Python


Download  Run Code

Output:

Inorder traversal of the constructed Cartesian tree is 9 3 7 1 8 12 10 20 15 18 5

The time complexity of the above solution is O(n2), where n is the total number of nodes in the Cartesian tree. The auxiliary space required by the program is O(h) for the call stack, where h is the height of the tree.