Connecting Tech Pros Worldwide Forums | Help | Site Map

traversing the tree and assigning the unique value for each node

Member
 
Join Date: May 2007
Posts: 47
#1: Nov 18 '07
Hello,

I am trying to traverse and tree and want to assign the node id for each node in the tree.

It would be great if someone helps me with it.

Here is the code which i am using and the problem is the nodes in the tree are repeating everytime and i want to visit each node only once and assign the node id to it.

protected void walk(TreeModel model, Object o){
int cc;
int x=1;

cc = model.getChildCount(o);
System.out.println(" childcount ==> "+cc);
for( int i=0; i < cc; i++) {
Object child = model.getChild(o, i );
if (model.isLeaf(child)){
System.out.println(" Leaf ==> "+child.toString());
TreeNode[] pathToRoot = ((DefaultMutableTreeNode)child).getPath();
System.out.println("Path==> "+((DefaultMutableTreeNode)child).getPath().toStri ng());

for (int j= 1; j < (pathToRoot.length)-1 ; j++ )
{
System.out.print(" ==> "+pathToRoot[j]);
System.out.print("insert into Node (Doc_ID, PNode_ID, Element) values ("+x +" ,"+ y +" , '" + pathToRoot[j] + "')");
storeDB("insert into Node (Doc_ID, PNode_ID, Element) values ('" + x +"' ,'"+ y +"' , '" + pathToRoot[j] + "')");
System.out.println("");
y++;

}
}

else {

System.out.print(child.toString()+"--");
walk(model,child );
}
}
}

public void storeDB (String insertSQL){
try {
Statement st = con.createStatement();
System.out.println("inserting***");
st.executeUpdate(insertSQL);
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}

JosAH's Avatar
Expert
 
Join Date: Mar 2007
Posts: 10,611
#2: Nov 19 '07

re: traversing the tree and assigning the unique value for each node


Quote:

Originally Posted by flavourofbru

Hello,

I am trying to traverse and tree and want to assign the node id for each node in the tree.

It would be great if someone helps me with it.

Recursion is the solution again. Suppose we have the following simple method:

Expand|Select|Wrap|Line Numbers
  1. int stamp(Node n, int id) {
  2.    n.id= id++;
  3.    return id;
  4. }
  5.  
All it does is stamp a node with an id value and return a next id value.

We can mark the entire tree in two ways:

Expand|Select|Wrap|Line Numbers
  1. public int mark(Node n, ind id) {
  2.  
  3.    if (n == null) return id; // nothing to mark
  4.  
  5.    id= stamp(n, id); // mark this node and
  6.  
  7.    for (Node child : children) { // mark its children
  8.       id= mark(child, id);
  9.    }
  10.  
  11.    // we could alternatively stamp this node afterwards here
  12.    // id= stamp(n, id);
  13.  
  14.    return id; // return the next available id value
  15. }
  16.  
kind regards,

Jos
Reply