heap ordering using binary tree

I have an assignment asking me to create a binary heap using binary tree instead of array. I have no idea about how to do this as what I got from internet/lecture is implement through ARRAY.

Code :

private static class Node {
public double value;
public Node left, right;
public Node(double value, Node left, Node right) {
this.value = value;
this.left = left;
this.right = right;
}

Code above is given, and I required to create an insert method. So, can you give me some general idea on how to do this?

thanks

Re: heap ordering using binary tree

Typically, nodes in a list have left and/or right values. nodes in a tree have children...see Binary Trees for an example of one type of tree: a binary tree

Re: heap ordering using binary tree

Code :

public void insert(double x){
size++;
root = insert(root, x);
}
private static Node insert(Node newnode, double x){
if(newnode == null){
newnode = new Node(x, null, null);
}
if(newnode.value < x) {
if((newnode.left != null) && (newnode.right != null)){
int n = (int)(10.0 * Math.random()) + 1;
if(n <= 5)
newnode.left = insert(newnode.left, x);
else
newnode.right = insert(newnode.right,x);
}
else{
if(newnode.left == null || newnode.right == null){
if(newnode.left == null)
newnode.left = new Node(x,null,null);
if(newnode.right == null)
newnode.right = new Node(x,null,null);
}
}
}
if(newnode.value > x){
double temp;
temp = newnode.value;
newnode.value = x;
insert(newnode, temp);
}

the above code is the insert method i tried to create. but it does not work. can you tell me why?

Re: heap ordering using binary tree

Quote:

Originally Posted by

**student**
the above code is the insert method i tried to create. but it does not work. can you tell me why?

Please define 'does not work'.

Re: heap ordering using binary tree

when i try to compile this code, it just simply cannot print out the right numbers. the first number was correct, but not the others.

Re: heap ordering using binary tree

Quote:

Originally Posted by

**student**
when i try to compile this code, it just simply cannot print out the right numbers. the first number was correct, but not the others.

This isn't the entire code listing, so we do not know what you've added to the tree/list, and how you are retrieving those values. Please provide a short example that clearly demonstrates the problem.