traverse all descendants of a node
Hello
I am wondering if it is possible to traverse all the descendants including children, greatchildren, greatgreatchildren, and so on, of a particular node? eg. how to only traverse the B1, B, C1, C2 and C through post iterator or B, B1, C and C1, C2 through pre iterator of the node A in this tree? (through a subtree of A could not be the best of my needs)
root
|
+----A
| |
| +---B
| | |
| | +---B1
| |
| +---C
| |
| +---C1
| |
| +---C2
+----D
|
+---E
|
+---F
Thank you.
Yes, that's not difficult. If it points to the node A of which you want to visit all descendants, do
auto end = it;
end.skip_children();
++end;
while( it != end) {
[do something with `it`]
++it;
}
The end.skip_children() is key here: it ensures that the following ++end will skip child nodes when determining what is the next node, effectively making it increment to D.
Hello, thank you so much for your prompt reply. I think the format of the previous tree is not clear. here is the correct one. so my question is how to only traverse all the descendants of the node A. eg B, B1, C, C1 and C2 via pre iterator or B1, B, C1, C2, C through post iterator. skip_children will go to node D, which is not the purpose. Thank you
root
|
+----A
| |
| +---B
| | |
| | +---B1
| |
| +---C
| |
| +---C1
| |
| +---C2
+----D
|
+---E
|
+---F
I use skip_children() on the end iterator, not on the it iterator which I use to traverse the subtree below A. So end points to D, and it, which initially points to A, is incremented to visit all children (and grandchildren and so on ) of A, until it comes back up and reaches D. At that point, the while loop will stop.
I see, thank you so much for your clear explanation. it works for the pre order iterator. traverse from B, B1, C, C1, C2 however, it seems not working for the post order iterator. any suggestions for traversing through B1, B, C1, C2, and C of node A. Thank you. treestd::string::iterator newloc = tre.iterator_from_path(path, tre.begin()); treestd::string::iterator newend = newloc; newend.skip_children(); ++newend; while(newloc != newend){ std::cout << "data" << newloc.node->data << "\n"; ++newloc; }
I also have another question: currently, i use auto it = std::find_if(tre.begin_post(), tre.end_post(), [&it](std::string* & itp) {return itp == "C"; }); or std::find_if(tre.begin(), tre.end(), [&it](std::string & itp) {return *itp == "C"; }); to search. is it possible to do std::find_if only in the A subtree, not the whole tree. thank you.