【算法题】二叉树非递归遍历
来源:互联网 发布:幻想神域数据库 编辑:程序博客网 时间:2024/05/22 05:07
先序遍历:入栈时访问
中序遍历:出栈时访问
后续遍历:第二次出栈时访问
#include <iostream>#include <vector>#include <numeric>#include<algorithm>#include <stack>#include <string>using namespace std;struct Tree{ double value; Tree* left; Tree* right;};void PreOrder(Tree * root)//先序遍历{ stack<Tree*> s; Tree* p = root; while (p != NULL || !s.empty()) { while (p != NULL) { cout << p->value<<" "; s.push(p); p = p->left; } if (!s.empty()) { p = s.top(); s.pop(); p = p->right; } }}void MidOrder(Tree * root)//中序遍历 { stack<Tree*> s; Tree * p = root; while (p != NULL || !s.empty()) { while (p != NULL) { s.push(p); p = p->left; } if (!s.empty()) { p = s.top(); s.pop(); cout << p->value << " "; p = p->right; } }}void PostOrder(Tree* root)//后序遍历{ struct Note { Tree * p; bool isFirst; }; stack<Note> s; Note tmp; Tree* p=root; while (p != NULL || !s.empty()) { while (p != NULL) { tmp.p = p; tmp.isFirst = true; s.push(tmp); p = p->left; } if (!s.empty()) { tmp = s.top(); s.pop(); if (tmp.isFirst == true) { p = tmp.p->right; tmp.isFirst = false; s.push(tmp); } else { cout << tmp.p->value << " "; p = NULL; } } }}int main(){ Tree root; Tree node1_1; Tree node1_2; Tree node2_1; Tree node2_2; Tree node2_3; Tree node3_1; Tree node3_2; Tree node3_3; Tree node3_4; root.value = 0; node1_1.value = 1.1; node1_2.value = 1.2; node2_1.value = 2.1; node2_2.value = 2.2; node2_3.value = 2.3; node3_1.value = 3.1; node3_2.value = 3.2; node3_3.value = 3.3; node3_4.value = 3.4; root.left = &node1_1; root.right = &node1_2; node1_1.left = &node2_1; node1_1.right = &node2_2; node1_2.left = &node2_3; node1_2.right = NULL; node2_1.left = &node3_1; node2_1.right = &node3_2; node2_2.left = NULL; node2_2.right = NULL; node2_3.left = &node3_3; node2_3.right = &node3_4; node3_1.left = NULL; node3_1.right = NULL; node3_2.left = NULL; node3_2.right = NULL; node3_3.left = NULL; node3_3.right = NULL; node3_4.left = NULL; node3_4.right = NULL; PreOrder(&root); cout << endl; MidOrder(&root); cout << endl; PostOrder(&root); cout << endl; return -1;}
阅读全文
0 0
- 【算法题】二叉树非递归遍历
- 二叉树遍历非递归算法
- 二叉树遍历的非递归算法
- 非递归遍历二叉树算法
- 二叉树遍历非递归算法
- 二叉树 遍历非递归算法
- 遍历二叉树的非递归算法
- 遍历二叉树的非递归算法
- 二叉树遍历算法非递归
- 二叉树遍历(非递归算法)
- 二叉树遍历非递归算法
- 二叉树遍历之非递归算法
- 二叉树遍历之非递归算法
- 非递归二叉树层次遍历算法
- 二叉树的遍历非递归算法
- 遍历二叉树的非递归算法
- 二叉树遍历算法(非递归)
- 二叉树遍历之非递归算法
- Andorid中的AIDL(二)
- QTcpServer、QTcpSocket、QUdpSocket在聊天程序上的应用
- TCP协议中的三次握手和四次挥手(图解)
- 基于多线程的随机数生成算法
- Struts(一)
- 【算法题】二叉树非递归遍历
- 第二章 人月神话
- java私有构造器
- Linux 中的信号
- 约会安排
- SparkGraphX快速入门
- thinkphp 修改进入默认首页
- C++ 动态内存分配
- 局部变量前不能加任何权限修饰符(private ,public protected)