Binary trees
I haven't been doing Java long and now getting into the more difficult things. I am simply trying to program a binary tree and insert nodes with data. The code I have so far is:
class tree_node
{
private Object data;//data stored in node
private tree_node left;//reference to left node
private tree_node right;//reference to right node
/*creates a new node with specified data, must also specify left and right values*/
public tree_node(Object initialData, tree_node initialLeft, tree_node initialRight)
{
data = initialData;
left = initialLeft;
right = initialRight;
}
public Object getData()
{
return data;
}
public tree_node getLeft()
{
return left;
}
public tree_node getRight()
{
return right;
}
publicvoid setData(Object newData)
{
data = newData;
}
publicvoid setLeft(tree_node newLeft)
{
left = newLeft;
}
publicvoid setRight(tree_node newRight)
{
right = newRight;
}
}
//first test of doing trees
class tree_test
{
publicstaticvoid main(String args[])
{
tree_node tree =new tree_node(20, null,null);
Object storeData, newData;
tree_node storeLeft, storeRight, newRight, newLeft;
storeData = tree.getData();
storeLeft = tree.getLeft();
storeRight = tree.getRight();
System.out.println("First\nThe data is "+storeData+"\nThe left node is "+storeLeft+"\nThe right node is "+storeRight);
//the above works fine
newRight = 43;
newLeft=new tree_node(40, null,null);
tree.setRight(newRight);//get an error saying incompatable types, which is correct, but how else do I place data in the node?
tree.setLeft(newLeft);//tried it this way and it compiles but when printing the screen it just has the reference to the node I created
storeData = tree.getData();
storeLeft = tree.getLeft();
storeRight = tree.getRight();
System.out.println("Second\nThe data is "+storeData+"\nThe left node is "+storeLeft+"\nThe right node is "+storeRight);
}
}
So I can create one node on its own and thats as far as I can get. I have looked at endless examples of code on the web all are useful for coding a binary tree but cant make sence of it. The book I have include packages which is not what I want, also have looked through archive forum questions on the site. Do I need another class or need to alter the class I already have? How do I do this? Help is much apprecated. Lisa

