class Node {
public int item;
public Node left;
public Node right;
}
public class CartesianTree {
public static Node build(int[] data) {
if (data == null || data.length == 0)
return null;
else
return build(data, 0, data.length - 1);
}
public static Node buildMirror(int[] data) {
if (data == null || data.length == 0)
return null;
else
return buildMirror(data, 0, data.length - 1);
}
private static Node build(int[] data, int start, int end) {
if (end < start)
return null;
int min = Integer.MAX_VALUE;
int minIndex = -1;
for (int i = start; i <= end; i++) {
if (data[i] < min)
{
min = data[i];
minIndex = i;
}
}
// System.out.println(minIndex);
// System.out.println(min);
Node node = new Node();
node.item = min;
node.left = build(data, start, minIndex - 1);
node.right = build(data, minIndex + 1, end);
return node;
}
private static Node buildMirror(int[] data, int start, int end) {
if (end < start)
return null;
int min = Integer.MAX_VALUE;
int minIndex = -1;
for (int i = start; i <= end; i++) {
if (data[i] < min)
{
min = data[i];
minIndex = i;
}
}
// System.out.println(minIndex);
// System.out.println(min);
Node node = new Node();
node.item = min;
node.right= buildMirror(data, start, minIndex - 1);
node.left= buildMirror(data, minIndex + 1, end);
return node;
}
public static void main(String[] args)
{
// int[]args1={10,9,8,7,6,5,4,3,2,1};
// int[]args1={1 , 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[]args1={4,3,5,7,2,9,8};
Node node = new Node();
node= build(args1);
System.out.println(node.left.item);
}
}