# heap ordering using binary tree

• October 27th, 2010, 11:33 AM
student
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
• October 27th, 2010, 11:56 AM
copeg
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
• October 27th, 2010, 12:46 PM
student
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?
• October 27th, 2010, 01:23 PM
copeg
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?