I am trying to create a complete binary tree using a linked list, instead of arraylist, without comparing node values. What I mean is on inserting a new value, I do not wish
The entire basis of a binary tree is on comparing values and sending them left or right down the tree.
Therefore, it is impossible to create a binary tree without comparisons.
But you did say upon insertion
, so you could add the item to the end of the list, and then sort it when you call for the tree. Like this:
list.add(value); //Just add the item to the end
call(); //This method would sort the list into a tree appropriately.
This option also allows you to change the type of tree dynamically, since you could add a parameter to call()
that specifies a tree type.
Keep a count of how many items you have in the tree.
Then, to add the n
th item follow the path created by dividing n
repeatedly by two and keeping track of the remainder. Follow the "route" created by the remainder in reverse: where 1 means right and 0 means left.
For example, to add the 11th item:
11/2 = 5 (1)
5/2 = 2 (1)
2/2 = 1 (0)
That means from the root, you'd go left, right, right.
It seems your question is unrelated to LinkedList. It was a little confusing.
If you know how many elements are in tree already, you can calculate the position from that number. It's binary representation is the path you have to take. See here.
If you don't know anything about current state of the tree, you need to do a Breadth-first search to find the first empty spot.