前序、中序、后序遍历二叉树的非递归实现
2015-02-24 15:32
155 查看
class Node { public: int data; Node* left; Node* right; }; void pre-order(Node* root) { stack<Node*> stk; if (root) stk.push(root); while (!stk.empty()) { Node* nd = stk.top(); cout << nd->data << endl; stk.pop(); if (nd->right) stk.push(nd->right); if (nd->left) stk.push(nd->left); } } void in-order(Node* root) { stack<Node*> stk; Node* nd = root; while (nd) { stk.push(nd); nd = nd->left; } while (!stk.empty()) { nd = stk.top(); cout << nd->data << endl; stk.pop(); Node* nd2 = nd->right; while (nd2) { stk.push(nd2); nd2 = nd2->left; } } } void post-order(Node* root) { // 使用双队列 stack<Node*> stk1, stk2; if (root) stk1.push(root); while (!stk1.empty()) { Node* nd = stk1.top(); stk1.pop(); stk2.push(nd); if (nd->left) stk1.push(nd->left); if (nd->right) stk1.push(rd->right); } while (!stk2.empty()) { Node* nd = stk2.top(); cout << nd->data << endl; stk2.pop(); } }
相关文章推荐
- 二叉树先序、中序、后序遍历的非递归实现
- 二叉树的遍历:前序、中序、后序、层序的非递归实现
- 利用栈实现二叉树的先序,中序,后序遍历的非递归操作
- 二叉树先序、中序、后序遍历的非递归实现
- 二叉树先序、中序、后序遍历的非递归实现
- 二叉树前序、中序、后序遍历的递归与非递归算法实现
- 二叉树先序,中序,后序遍历非递归实现
- 二叉树的前序、中序、后序遍历 递归非递归实现
- ZT 二叉树先序,中序,后序遍历非递归实现
- 二叉树的遍历:前序,中序,后序,层序--包括递归和非递归实现
- 二叉树的遍历:前序,中序,后序,层序--包括递归和非递归实现
- 二叉树的遍历 前序 中序 后序 分别实现递归和非递归遍历方式
- 用非递归实现二叉树的前序、中序、后序、层次遍历,用递归实现查找、统计个数、比较、求深度
- 二叉树的遍历:前序,中序,后序,层序--包括递归和非递归实现
- java语言实现二叉树的前序、中序与后序遍历(递归与非递归)
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 二叉树的创建,先序、中序、后序遍历的递归实现以及层序遍历
- [转]非递归实现二叉树的前序,中序,后序遍历
- 二叉树先序、中序、后序遍历的非递归实现,纯c代码
- 二叉树的遍历(前序、中序、后序、层序),递归和非递归实现