C++遍历二叉树的设计问题
我有一个二叉树 T,我想将其复制到另一棵树。
假设我有一个在每个节点上进行评估的访问方法:
struct visit
{
virtual void operator() (node* n)=0;
};
并且我有一个访问者算法,
void visitor(node* t, visit& v)
{
//do a preorder traversal using stack or recursion
if (!t) return;
v(t);
visitor(t->left, v);
visitor(t->right, v);
}
我有两个问题:
- 我决定使用基于函子的方法,因为我看到提升图可以做到这一点(顶点访问者)。我也倾向于重复相同的代码来遍历树并做不同的事情 在每个节点。这是一个消除重复代码的好设计吗?还有哪些其他替代设计?
- 如何使用它从现有的二叉树创建一棵新的二叉树?我可以在上面保留一个堆栈 如果我愿意,可以访问函子,但它与访问者中的算法相关联。
- 我如何在这里合并后序遍历?另一个函子类?
I have a binary tree T which I would like to copy to another tree.
Suppose I have a visit method that gets evaluated at every node:
struct visit
{
virtual void operator() (node* n)=0;
};
and I have a visitor algorithm
void visitor(node* t, visit& v)
{
//do a preorder traversal using stack or recursion
if (!t) return;
v(t);
visitor(t->left, v);
visitor(t->right, v);
}
I have 2 questions:
- I settled on using the functor based approach because I see that boost graph does this (vertex visitors). Also I tend to repeat the same code to traverse the tree and do different things
at each node. Is this a good design to get rid of duplicated code? What other alternative designs are there? - How do I use this to create a new binary tree from an existing one? I can keep a stack on the
visit functor if I want, but it gets tied to the algorithm in visitor. - How would I incorporate postorder traversals here ? Another functor class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
3:为您想要执行的每种类型的遍历创建一个附加方法并重新安排访问者调用:
3: Create an additional method for each type of traversal you want to do and rearrange the visitor calls:
访客是一种技术。看起来您已经将该技术与特定解决方案混淆了。使用访问者意味着某些导航服务由数据结构提供,该数据结构将通过回调与外部对象(访问者)进行通信。
A visitor is a technique. It looks like you've confused the technique with a particular solution. Using a visitor means that some navigation services are provided by the data structure which will communicate with an external object (the visitor) by call-back.