private static void insertElement(
TreeNode node,
TreeElement element,
Result result,
TreeOperations operations) throws Exception {
Interval elemInt = element.getInterval();
if( false == elemInt.isIncludedIn(node.getInterval()) ){
// Must grow interval
node.extendTo( element.getInterval() );
result.treeModified = true;
}
if( elemInt.getMax() <= node.getMidPoint()
&& null != node.getLowChildNode() ){
insertElement(node.getLowChildNode(), element, result, operations);
} else if( elemInt.getMin() >= node.getMidPoint()
&& null != node.getHighChildNode() ){
insertElement(node.getHighChildNode(), element, result, operations);
} else {
// Check if low should be created
if( null == node.getLowChildNode()
&& elemInt.getMax() <= node.getMidPoint() ){
int count = 1;
List<TreeElement> nodeElements = operations.getElementsForClusterId(node.getClusterId());
for(TreeElement nodeElement : nodeElements){
if( nodeElement.getInterval().getMax() <= node.getMidPoint() ){
++count;
}
}
if( count > NODE_ELEMENT_THRESHOLD ){
// Should create low
int clusterId = result.getNextClusterId();
Interval childInt = new Interval(node.getInterval().getMin(), node.getMidPoint());
TreeNode childNode = new TreeNode(clusterId,childInt);
node.setLowChildNode(childNode);
result.treeModified = true;
result.insert(clusterId, element);
return; // done
}
}
// Check if high should be created
if( null == node.getHighChildNode()
&& elemInt.getMin() >= node.getMidPoint() ){
int count = 1;
List<TreeElement> nodeElements = operations.getElementsForClusterId(node.getClusterId());
for(TreeElement nodeElement : nodeElements){
if( nodeElement.getInterval().getMin() >= node.getMidPoint() ){
++count;
}
}
if( count > NODE_ELEMENT_THRESHOLD ){
// Should create low
int clusterId = result.getNextClusterId();
Interval childInt = new Interval(node.getMidPoint(), node.getInterval().getMax());
TreeNode childNode = new TreeNode(clusterId,childInt);
node.setHighChildNode(childNode);
result.treeModified = true;
result.insert(clusterId, element);