在C++中寻找简单树迭代的例子,包括递归迭代和迭代迭代。 (post,pre和in order)树迭代C++
Q
树迭代C++
0
A
回答
1
This page显示二叉树的示例以及如何遍历它。
2
Adobe Source Library的adobe::forest<T>
是一个通用树型容器,可以在预先或按顺序进行迭代。该文档具有如何完成这些不同类型的迭代的示例。
1
如果你的树是这个样子:
struct Node{
Node *left, *right, *parent;
int value; // or some other important data :-)
}
那么这就是你如何使阶递归迭代:
void iterate(Node *n){
if(!n)
return;
iterate(n->left);
cout << n->value; // do something with the value
iterate(n->right);
}
如果换用正线>左和n - >右边的树会以相反的顺序迭代。
这些都是前期的整理和后序迭代:
void iterate_pre(Node *n){
if(!n)
return;
cout << n->value; // do something with the value
iterate_pre(n->left);
iterate_pre(n->right);
}
void iterate_post(Node *n){
if(!n)
return;
iterate_post(n->left);
iterate_post(n->right);
cout << n->value; // do something with the value
}
非递归迭代是一个稍微复杂一些。 你需要的第一件事就是找到在树中的第一个节点(如vector<T>::begin()
)
Node *find_first(Node *tree){
Node *tmp;
while(tree){
tmp = tree;
tree = tree->left
}
return tmp;
}
然后,你需要一种方式来获得树(vector<T>::iterator::operator++()
)的下一个项目。
Node *next(Node *n){
assert(n);
if(n->right)
return find_first(n->right)
while(n->parent && n->parent->right == n)
n = n->parent;
if(!n->parent)
return NULL;
return n;
}
(此功能试图找到在右子树第一个节点,如果这是不可能的,上升的树,直到路径来自右子树)
相关问题
- 1. AVL树迭代器在C
- 2. 迭代树走
- 3. 迭代从树
- 4. 二叉搜索树inorder迭代器C++
- 5. C++迭代销毁二叉树
- 6. 迭代TreeSet的 - 从树状
- 7. 如何迭代DOM树?
- 8. Wxpython:TreeCtrl:在树上迭代
- 9. 如何迭代k-ary树?
- 10. 递归迭代(在Python树)
- 11. 迭代八叉树遍历
- 12. Java中的树迭代器
- 13. 迭代器中的迭代器在树型集合中的迭代器
- 14. C++迭代
- 15. 迭代IN C#
- 16. C++迭代和反向迭代
- 17. C++ AVL树迭代器不会正确递增
- 18. 微型优化迭代通过一棵树在C#
- 19. C中的非递归/迭代二叉搜索树(作业)
- 20. 在C++中建模任意树(使用迭代器)
- 21. C++,实现二叉树的自定义迭代器(长)
- 22. 向后迭代C++
- 23. 迭代通过c#
- 24. C++迭代混乱
- 25. 迭代使用C++
- 26. C - 迭代多叉
- 27. C++迭代器类
- 28. C++迭代难题
- 29. LevelDB C迭代器
- 30. R和C++迭代
你iterate_pre和iterate_post应该称自己不是迭代。 – sbk 2009-09-21 19:03:38
你说得对,谢谢:-) – cube 2009-09-21 19:12:17