非递归和递归方法遍历二叉树
来源:互联网 发布:掌酷主题软件 编辑:程序博客网 时间:2024/05/19 17:24
</pre><p><pre class="cpp" name="code">struct node { int value; struct node * left; struct node * right;};void preOrderBTree(struct node * head) {if (head == NULL)return;stack<struct node *> s;s.push(head);while (!s.empty()) {struct node * tmp = s.top();cout << tmp->value << " ";s.pop();if (tmp->right != NULL)s.push(tmp->right);if (tmp->left != NULL)s.push(tmp->left);}cout << endl;}
<pre class="cpp" name="code">void circuseBTreePreOrder(struct node * head) {if (head == NULL)return;cout << head->value << " ";circuseBTreePreOrder(head->left);circuseBTreePreOrder(head->right);}
void anotherPreOrder(struct node * head) {if (head == NULL)return;stack<struct node *> s;s.push(head);cout << head->value << " ";struct node * tmp = head->left;while (1) {while (tmp != NULL) {s.push(tmp);cout << tmp->value << " ";tmp = tmp->left;}if (s.empty())break;tmp = s.top()->right;s.pop();}}
非递归中序遍历二叉树:
void midOrder(struct node * head) {if (head == NULL)return;struct node * tmp = head->left;stack<struct node *> s;s.push(head);while (1) {while (tmp != NULL) {s.push(tmp);tmp = tmp->left;}if (s.empty())break;tmp = s.top()->right;cout << s.top()->value << " ";s.pop();}}
层次遍历二叉树:
void layerOrder(struct node * head) {if (head == NULL)return;queue<struct node *> q;;q.push(head);while (!q.empty()) {struct node * cur = q.front();q.pop();cout << cur->value << " ";if (cur->left != NULL) {q.push(cur->left);}if (cur->right != NULL) {q.push(cur->right);}}}
非递归后序遍历二叉树:
void postOrder(struct node * head) {if (head == NULL)return;stack<struct node *> s;struct node * r = NULL;s.push(head);struct node * tmp = head->left;int flag = 0;while (!s.empty()) {while (tmp != NULL) {s.push(tmp);tmp = tmp->left;}if (s.top() == head) {flag++;}if (flag == 2) {cout << s.top()->value << " ";break;}if ((s.top()->right == NULL) || (s.top() == r)) {cout << s.top()->value << " ";s.pop();tmp = NULL;}else {tmp = s.top()->right;r = s.top();}}}
时间复杂度: O(n)
递归的中序遍历和后序遍历方法与文中的前序遍历方法相同,不同的地方就是打印输出的位置。
0 0
- 非递归和递归方法遍历二叉树
- 二叉树的遍历 -- 递归和非递归方法
- 二叉树遍历,递归和非递归方法
- 二叉树的递归和非递归遍历方法
- 二叉树的递归和非递归遍历方法
- 递归 和 非递归 遍历二叉树
- 递归和非递归遍历二叉树
- 递归和非递归遍历二叉树
- 二叉树递归和非递归遍历
- 二叉树递归和非递归遍历
- 递归和非递归遍历二叉树
- 二叉树递归遍历和非递归遍历
- 二叉树的递归遍历和非递归遍历
- 二叉树递归遍历和非递归遍历
- 二叉树递归遍历和非递归遍历
- 二叉树的递归遍历和非递归遍历
- 二叉搜索树的递归遍历和非递归遍历
- java 二叉树的递归遍历和非递归遍历
- 下一个七年
- android:sharedUserId问题
- qlistView中添加右键菜单
- 数据库索引的作用和优点缺点
- delphi7 安装/卸载控件通用方法
- 非递归和递归方法遍历二叉树
- linux vi编辑器命令学习
- python 编码转换
- VS2008和VS2010中禁用及卸载Visual Assist X
- 注册表关闭IDE通道
- WaveFax传真服务器系统如何工作?
- 搭建自己的PHP框架
- 蓝桥杯——操作格子
- 电脑基础知识