Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: heap ordering using binary tree

1. ## 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.

```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

2. ## 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

3. ## Re: heap ordering using binary tree

``` 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?

4. ## Re: heap ordering using binary tree

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?