每天一道算法题(38)——二叉树的非递归遍历
2015-10-13 20:46
465 查看
#include<iostream> #include "stack" using namespace std; struct node{ char c; node* left; node *right; bool flag; }; void pre(node* head){//非递归前序遍历 stack<node*> s; while (head || !s.empty()){ if (head){ cout << head->c; s.push(head); head = head->left; } else{ head = s.top()->right; s.pop(); } } } void middle(node* head){//非递归中序遍历 stack<node*> s; node* p; while (head || !s.empty()){ if (head){ s.push(head); head = head->left; } else{ p = s.top(); cout << p->c; s.pop(); head = p->right; } } } void post(node* head){//非递归后序遍历 node* p; stack<node*> s; while (head || !s.empty()){ if (head){ s.push(head); head = head->left; } else{ p = s.top(); if (p->flag){ cout << p->c; s.pop(); } else{ head = p->right; p->flag = true;//代表右子树已经访问过 } } } } int main(int argc, char **argv) { node f = { 'f', 0, 0, false }; node e = { 'e', &f, 0, false }; node d = { 'd', 0, 0, false }; node b = { 'b', &d, &e, false }; node g = { 'g', 0, 0, false }; node c = { 'c', 0, &g, false }; node a = { 'a', &b, &c, false }; pre(&a); cout << endl; middle(&a); cout << endl; post(&a); }
相关文章推荐
- grails2.3.11第一课
- hdu 5344 MZL's xor
- 51nod 1179:最大的最大公约数
- 马士兵Java课堂笔记-2-基本数据类型转换问题
- BZOJ 3158: 千钧一发(最小割)
- 斗地主- (三)
- 重拾ionic
- 10.13做题——洛谷1449后缀表达式
- C++运行结果中让控制台停住的办法
- iOS之CocoaPods 安装
- Mysql支持的数据类型
- hdu 统计难题(map)
- getchar、getch、getche
- leetcode32
- 3.Maximum Depth of Binary Tree
- hadoop2.6+ zookeeper3.4.6搭建
- java 策略模式
- wifi调试android 设备的方法
- openfire源码分析---1
- 二叉树前序遍历