I need to make a Complete Binary Search Tree
.
If I have a method that looks like this:
public void createCompleteTree(Node n, int i)
And I for example use the number 9 as the i
value, what do I do to find a root that will make a complete tree?
If I use 9 as the value, the numbers would be 1,2,3,4,5,6,7,8,9
.
For a complete Binary search tree, the root must be 6, like below:
How can I make a method that knows this? It should work with any kind of number, so if I want to use number 14 it should be able to.
So far the only code I have is an insert method, which just checks if the number to be inserted is greater (goes to the right) or smaller (goes to the left) than the node we are currently at. x
is the number to be inserted, t
is the current node we are at in the tree:
private BinaryNode<AnyType> insert( AnyType x, BinaryNode<AnyType> t )
{
if( t == null )
return new BinaryNode<>( x, null, null );
int compareResult = x.compareTo( t.element );
if( compareResult < 0 )
t.left = insert( x, t.left );
else if( compareResult > 0 )
t.right = insert( x, t.right );
else
; // Duplicate; do nothing
return t;
}