C++ TCL(树容器库):如何从节点直接遍历树到根
我正在使用这个库来保存有关树结构的信息:
http://www.datasoftsolutions.net/ tree_container_library/overview.php
这是我的 C++ 代码的简化版本:
#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;
}
树看起来像这样
0
|_ 1
|_ 2
|_ 3
|_4
|_5
|_6
我正在尝试创建一个函数,给定 Node(6) 将遍历通向根的所有节点,即 6 ,5,3,0。这是我的第一个 C++ 项目,我在理解指针方面遇到了困难。可能是几行 C++,但我尝试了几个小时,但没有成功。任何帮助将不胜感激。
像这样的东西是有效的,但它必须适用于许多级别,而不仅仅是 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();
I am using this library 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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
常见的方法是使用这样的东西
也许你必须使用 while (tmp->has_parent()) 或类似的东西。
the common method is to use something like this
Maybe you have to use
while (tmp->has_parent())
or something like that instead.奥托是对的:)
我最终使用的是定义一个指向游戏树的指针。然后使用 ->is_root() 方法遍历节点。
Otto was right :)
What I ended up using is defining a pointer to gametree. And then traverse the nodes using ->is_root() method.