在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. C#中的二叉樹迭代#
- 5. C++迭代銷燬二叉樹
- 6. 二叉搜索樹inorder迭代器C++
- 7. 如何迭代DOM樹?
- 8. 迭代TreeSet的 - 從樹狀
- 9. Wxpython:TreeCtrl:在樹上迭代
- 10. 迭代八叉樹遍歷
- 11. 如何迭代k-ary樹?
- 12. 迭代更新scalaz樹
- 13. 遞歸迭代(在Python樹)
- 14. Java中的樹迭代器
- 15. 迭代器中的迭代器在樹型集合中的迭代器
- 16. C++迭代
- 17. C++ set_union迭代
- 18. 迭代與C++
- 19. C#迭代MapLocationFinderResult
- 20. 迭代IN C#
- 21. C#IList迭代
- 22. 迭代在C++
- 23. C++迭代器
- 24. C++ - 迭代器迭代器不編譯
- 25. C++迭代和反向迭代
- 26. 異類迭代器的C++迭代器
- 27. 迭代器無故迭代C++
- 28. 在C++中建模任意樹(使用迭代器)
- 29. C中的非遞歸/迭代二叉搜索樹(作業)
- 30. C++ AVL樹迭代器不會正確遞增
你iterate_pre和iterate_post應該稱自己不是迭代。 – sbk 2009-09-21 19:03:38
你說得對,謝謝:-) – cube 2009-09-21 19:12:17