我有一个基于 vector 的二叉树,需要使用各种遍历方法将函数应用于树中的每个值。使用递归函数可以很容易地实现前序遍历,但是我在使用中序和后序遍历执行同样的操作时遇到了麻烦。如果有人可以提供帮助那就太好了!
我应该包含的一些额外信息: 我使用的是节点 vector ,每个节点都包含一个 bool 变量(说明该节点是否已填充)和一个模板化数据变量。每个节点存储在索引“i”处,而其左子节点位于索引“2i+1”处,右子节点位于“2i+2”处。
为了对列表应用前序遍历,我首先处理存储在索引 0 处的数据,然后调用此递归函数
template <typename Item, typename Key>
template <typename Function>
void BST<Item,Key>::preTraverse(int n, Function f) {
if(tree[n].occupied == false) return;
else {
f(tree[n].data);
preTraverse(2*i+1,f);
preTraverse(2*i+2,f);
}
}
两次以索引 1 和 2 开始作为我的“n”参数。
最佳答案
预购:
do something with the value
f(go to the left)
f(go to the right)
有序:
f(go to the left)
do something with the value
f(go to the right)
邮购:
f(go to the left)
f(go to the right)
do something with the value
关于c++ - 基于 vector 的二叉树遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13557469/