• Post Reply Bookmark Topic Watch Topic
  • New Topic

Traversing TreeNode  RSS feed

 
Pappu Kumar
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a TreeNode....which may or may not have children. These children may or may not have children (The children are of type TreeNode too) too. I have to loop thru this TreeNode on an JSP page and display some text based on the properties of the TreeNode that i visit.

There is something wrong with my current loop as it drills down to the deepest TreeNode and forgets the rest. For Example :

TreeNode A has two Children - TreeNode AA and TreeNode AB.
TreeNode AA has two Children AAA and AAAA.
TreeNode AB doesnt have any children.

My current loop visits TreeNode A and TreeNode AA and both its children.
But somehow skips TreeNode AB.

Can you please tell me whats wrong with this peice of code.

public void createNodes(TreeNode tnode,JspWriter out){
Collection children = tnode.getChildren().values();
if(children.size() == 0)
out.println("Info abt this treenode");
}
else{
out.println("Info abt this treenode");
for(Iterator iter = children.iterator(); iter.hasNext() {
createNodes(tnodeChild,out);
}
}

Can some please suggest whats wrong here....

regards
Pappu
 
Dave Wingate
Ranch Hand
Posts: 262
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
looks like you're problem is in:



You are creating an iterator, but never removing items from it. Instead of:
createNodes(tnodeChild,out);

Try something like:
createNodes((TreeNode) iter.next(),out);
 
Pappu Kumar
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am sorry i didnt publish the complete code.
But i do have this -

for(Iterator iter = children.iterator(); iter.hasNext() {
TreeNode tnodeChild = (TreeNode) iter.next();
createNodes(tnodeChild,out);

}
 
fred Joly
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

What do you mean by "TreeNode"? Do you mean the interface "TreeNode" in "javax.swing.tree". In that case you should use the methods from the interface (isLeaf(), children(), ....).
Or TreeNode is a class you wrote yourself that does not implement above TreeNode ?
In both case could you show us your implementation, so we coudl help.
Your algorithm looks OK, so maybe that your method "getChildren()" or the way you add a child to a treeNode are wrong.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!