以下给出了三种遍历的迭代器算法。
class Iterator { public: virtual TreeNode* next() = 0; }; class PreOrderIterator : public Iterator { public: PreOrderIterator(TreeNode * root) { if(root) s.push(root); } virtual TreeNode* next() { TreeNode *top(nullptr); if(!s.empty()) { top = s.top(); s.pop(); if(top->right_child) s.push(top->right_child); if(top->left_child) s.push(top->left_child); } return top; } private: stack<TreeNode*> s; }; class InOrderIterator : public Iterator { public: InOrderIterator(TreeNode * root) { while(root) { s.push(root); root = root->left_child; } } virtual TreeNode* next() { TreeNode *top(nullptr); TreeNode *cur(nullptr); if(!s.empty()) { top = cur = s.top(); s.pop(); cur = cur->right_child; while(cur) { s.push(cur); cur = cur->left_child; } } return top; } private: stack<TreeNode*> s; }; class PostOrderIterator : public Iterator { public: PostOrderIterator(TreeNode *root): pre(nullptr) { while(root) { s.push(root); root = root->left_child; } } virtual TreeNode* next() { TreeNode *cur(nullptr); while(cur || !s.empty()) { while(cur) { s.push(cur); cur = cur->left_child; } cur = s.top(); s.pop(); if(nullptr == cur->right_child || pre == cur->right_child) { //right_child is nullptr or already visited pre = cur; return cur; } else { s.push(cur); cur = cur->right_child; } } return nullptr; } private: TreeNode *pre; //previously visited node stack<TreeNode*> s; };
上述迭代器的使用方法如下:
PostOrderIterator iter(root); TreeNode *node = iter.next(); while(node) { cout << node->value << " "; node = iter.next(); } cout << endl;
数据结构 《22》---- 二叉树三种遍历的迭代器算法,布布扣,bubuko.com
原文地址:http://blog.csdn.net/shoulinjun/article/details/37517627