问题
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 to compare if the value is less, greater or equal than the root's value, so as to add it either to the left link or to the right link, but still be able to create a complete binary tree.
Do you think it's possible? If yes, do you have any idea or can you point me to something I can use/read to do it?
EDIT:
Here's an example to make my question more clear: I am adding the numbers in the order presented through the insert method: 1 2 3 4 5 6 the insert method takes care of the structure of the tree. 1 becomes the root since it's the first value added. 2 is the left child of 1 3 the right child of 1 4 the left child of 2 5 the right child of 2 6 the left child of 3
SOLUTION:
public void insert(Comparable item) {
total++;
if (root == null) {
root = new TreeNode(item);
} else {
int quotient=total;
Stack path = new Stack();
TreeNode p = root; // helper node to follow path
quotient /= 2; // skip last step
while (quotient>1) { // build path to follow
path.push(quotient%2);
quotient /= 2;
}
while (!path.isEmpty()) {
Object q = path.pop();
if (q.equals(0))
p = p.getLeft();
else
p = p.getRight();
}
if (total%2==0) // check last step
p.setLeft(new TreeNode(item));
else
p.setRight(new TreeNode(item));
}
}
回答1:
Keep a count of how many items you have in the tree.
Then, to add the nth 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.
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/8460955/create-a-complete-binary-tree-using-linked-lists-w-o-comparing-node-values