• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

add method in a tree class

 
Ranch Hand
Posts: 167
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi, I am trying to implement a simple binary tree class, but I don't know why my add method doesn't work. My TreeNode class is quite simple with only 3 fields, Comparable data, TreeNode lchild, rchild;public class Tree{
TreeNode current, root;
class TreeNode{
Comparable data;
TreeNode lchild, rchild;
TreeNode(TreeNode lc, Comparable d, TreeNode rc){
data=d;
lchild=lc;
rchild=rc;
}
}
/*void add(Comparable o){
if(root==null){
root = new TreeNode(null, o, null);
}
else
add(root, o);
}*/
Tree(){
root=current;
}
public void add(Comparable o){
if(root==null){
root=new TreeNode(null, o, null);
current = root;
return;
}
if(current==null){
current = new TreeNode(null, o, null);
current = root;
return;
}
else{
if(current.data.compareTo(o)>0){
current = current.lchild;
add(o);
}
else{
current = current.rchild;
add(o);
}
}
}
void traversal(TreeNode current){
if(current==null)
return;
else{
traversal(current.rchild);
System.out.println("preorder traversal:"+current.data);
traversal(current.lchild);
}
}
void printLeft(){
if(current==null){
current=root;
return;
}
else{
System.out.println("*.current.data="+current.data+" current.lchild="+current.lchild);
current=current.lchild;
printLeft();
}
}

public static void main(String[] args){
Tree t = new Tree();
for(int i=0; i<Integer.parseInt(args[0]); i++)
t.add(new Integer((int)(100*Math.random())));
t.printLeft();
}
}
 
Paddy spent all of his days in the O'Furniture back yard with this tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic