3

I'm working on a TreeDecomposition where each node in a tree can have more than one vertices from the graph.
Now, i'm trying to find the first node which contains a vertex u from the root of tree.

int Tree::traversing(Node* node, int u){ 
    //search in current node
    int j = node->point_in_bag(u); //this function returns position of vertex u in node if not available -1
    if(j != -1){
       return node->index;
    }
    else{       
    // traverse in its children
    for(int k=0; k<node->children.size(); k++){ // children has the node's childs in it
        Node* nod = node->children[k];
        cout << "nod index is " << nod->index << endl;
        traversing(nod,u); // if vertex isn't found in node, traverse again in its children
        }
    }
}

i have tried like above, but its not returning the exact node index. where am i doing wrong.

timrau
  • 22,578
  • 4
  • 51
  • 64
user322
  • 103
  • 8
  • Your indentation and comments are a mess. In fact some of the characters that obviously ought to be in comments aren't, thus rendering the code malformed. Please make an effort to present readable code for others to review. – Marcelo Cantos Mar 06 '13 at 09:26
  • sorry for that. i will try to improvise it. – user322 Mar 06 '13 at 09:35
  • This problem is one elementary in algorithmic. First try to understand how can be traverse binary tree in recursive or non recursive manner. – Mihai8 Mar 06 '13 at 09:38

1 Answers1

2

You forgot a return here:

traversing(nod,u);

so your recursive call is returning some random data (and has undefined behaviour).

Even if you had returned, you would only return the index from the first child.
You need to keep looking if it isn't found.

for(int k=0; k<node->children.size(); k++){
    Node* nod = node->children[k];
    int childIndex = traversing(nod,u);
    if (childIndex != -1)
        return childIndex;
}
return -1;

You should increase the warning level on your compiler.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82
  • @user2139106 Enable warnings in your compiler. It should be able to catch cases where functions return nothing. Or, if they are enabled, don't ignore them. – Alexey Frunze Mar 06 '13 at 09:39
  • @KarolyHorvath Yes. i'm able to traverse only the first child. I have to look in to fix that now. thanks for pointing that soo early. – user322 Mar 06 '13 at 09:48
  • @KarolyHorvath Oops, I missed that part. – molbdnilo Mar 06 '13 at 09:51