traversing the tree and assigning the unique value for each node

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • flavourofbru
    New Member
    • May 2007
    • 48

    #1

    traversing the tree and assigning the unique value for each node

    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.getChildC ount(o);
    System.out.prin tln(" childcount ==> "+cc);
    for( int i=0; i < cc; i++) {
    Object child = model.getChild( o, i );
    if (model.isLeaf(c hild)){
    System.out.prin tln(" Leaf ==> "+child.toStrin g());
    TreeNode[] pathToRoot = ((DefaultMutabl eTreeNode)child ).getPath();
    System.out.prin tln("Path==> "+((DefaultMuta bleTreeNode)chi ld).getPath().t oString());

    for (int j= 1; j < (pathToRoot.len gth)-1 ; j++ )
    {
    System.out.prin t(" ==> "+pathToRoo t[j]);
    System.out.prin t("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.prin tln("");
    y++;

    }
    }

    else {

    System.out.prin t(child.toStrin g()+"--");
    walk(model,chil d );
    }
    }
    }

    public void storeDB (String insertSQL){
    try {
    Statement st = con.createState ment();
    System.out.prin tln("inserting* **");
    st.executeUpdat e(insertSQL);
    } catch (Exception e) {
    System.err.prin tln("Got an exception! ");
    System.err.prin tln(e.getMessag e());
    }
    }
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    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:

    [code=java]
    int stamp(Node n, int id) {
    n.id= id++;
    return id;
    }
    [/code]

    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:

    [code=java]
    public int mark(Node n, ind id) {

    if (n == null) return id; // nothing to mark

    id= stamp(n, id); // mark this node and

    for (Node child : children) { // mark its children
    id= mark(child, id);
    }

    // we could alternatively stamp this node afterwards here
    // id= stamp(n, id);

    return id; // return the next available id value
    }
    [/code]

    kind regards,

    Jos

    Comment

    Working...