C++ TCL (tree container library): How to traverse a tree from a node straight to root
I am using this librar开发者_开发技巧y to hold information about tree structure:
http://www.datasoftsolutions.net/tree_container_library/overview.php
Here is simplified version of my C++ code:
#include "tcl/sequential_tree.h"
// Node has some data which is not important now
typedef sequential_tree<Node> gametree_t;
typedef sequential_tree<Node>::iterator gametree_iter;
int main() {
gametree_t gametree;
gametree_iter gametree_it;
gametree_it = gametree.insert(Node(0));
gametree_it->insert(Node(1));
gametree_it->insert(Node(2));
gametree_it = gametree_it->insert(Node(3));
gametree_it->insert(Node(4));
gametree_it = gametree_it->insert(Node(5));
gametree_it->insert(Node(6));
return 1;
}
The tree looks like this
0
|_ 1
|_ 2
|_ 3
|_4
|_5
|_6
I am trying to make a function which given the Node(6) will traverse all the nodes leading to root i.e 6,5,3,0. This is my first project in C++ and I have trouble understanding pointers. Probably it is a few lines of C++ but I'm trying to do this for a couple of hours with no success. Any help will be appreciated.
something like this works but it must work with many levels not only with 4:
gametree_it->get()->get_value();
gametree_it->parent()->get()->get_value();
gametree_it->parent()->parent()->get()->get_value();
gametree_it->parent()->parent()->parent()->get()->get_value();
the common method is to use something like this
Node tmp = gametree_it;
while (tmp->parent() != NULL) {
tmp = tmp->parent();
}
root = tmp->get();
Maybe you have to use while (tmp->has_parent())
or something like that instead.
Otto was right :)
What I ended up using is defining a pointer to gametree. And then traverse the nodes using ->is_root() method.
gametree_t* gametree_p;
gametree_p = gametree_it.node(); // gets current node
while (!gametree_p->is_root()) {
cout << gametree_p->get()->get_value() << endl;
gametree_p = gametree_p->parent();
}
精彩评论