#include<bits/stdc++.h>
struct
Node
{
int
data;
Node *left, *right;
};
void
printInorder (Node* node)
{
if
(node == NULL)
return
;
printInorder (node->left);
cout << node->data <<
" "
;
printInorder (node->right);
}
Node * buildCartesianTreeUtil (
int
root,
int
arr[],
int
parent[],
int
leftchild[],
int
rightchild[])
{
if
(root == -1)
return
NULL;
Node *temp =
new
Node;
temp->data = arr[root] ;
temp->left = buildCartesianTreeUtil( leftchild[root],
arr, parent, leftchild, rightchild );
temp->right = buildCartesianTreeUtil( rightchild[root],
arr, parent, leftchild, rightchild );
return
temp ;
}
Node * buildCartesianTree (
int
arr[],
int
n)
{
int
parent[n],leftchild[n],rightchild[n];
memset
(parent, -1,
sizeof
(parent));
memset
(leftchild, -1,
sizeof
(leftchild));
memset
(rightchild, -1,
sizeof
(rightchild));
int
root = 0, last;
for
(
int
i=1; i<=n-1; i++)
{
last = i-1;
rightchild[i] = -1;
while
(arr[last] <= arr[i] && last != root)
last = parent[last];
if
(arr[last] <= arr[i])
{
parent[root] = i;
leftchild[i] = root;
root = i;
}
else
if
(rightchild[last] == -1)
{
rightchild[last] = i;
parent[i] = last;
leftchild[i] = -1;
}
else
{
parent[rightchild[last]] = i;
leftchild[i] = rightchild[last];
rightchild[last] = i;
parent[i] = last;
}
}
parent[root] = -1;
return
(buildCartesianTreeUtil (root, arr, parent,
leftchild, rightchild));
}
int
main()
{
int
arr[] = {5, 10, 40, 30, 28};
int
n =
sizeof
(arr)/
sizeof
(arr[0]);
Node *root = buildCartesianTree(arr, n);
printf
(
"Inorder traversal of the constructed tree : \n"
);
printInorder(root);
return
(0);
}