先根遍历__非递归操作
来源:互联网 发布:淘宝店主自拍技巧 编辑:程序博客网 时间:2024/05/22 05:22
// 先序(附带叶子标记)建树#include<iostream>#include<stdio.h>#include<stdlib.h>#include<string.h>#include<stack>#include<string>using namespace std;struct node{ char data; node* lchild; node* rchild;};void buildtree(char* str,node* root){ stack<node*> sta; int pos = 0; int len = strlen(str); node* tmp; root->data = str[pos++]; root->lchild = NULL; root->rchild = NULL; sta.push(root); while(pos < len) { while(true) { node* nl = new node; nl->data = str[pos]; nl->lchild = NULL; nl->rchild = NULL; if(str[pos]=='*') { free(nl); break; } sta.top()->lchild = nl; sta.push(nl); ++pos; } tmp = sta.top(); sta.pop(); ++pos; while(str[pos]=='*') { if(!sta.empty()) { tmp = sta.top(); sta.pop(); } ++pos; } if(pos >= len) break; node* nr = new node; nr->data = str[pos]; nr->lchild = NULL; nr->rchild = NULL; sta.push(nr); tmp->rchild = nr; ++pos; } return;}// 先根遍历,入栈的时候输出// 注意,有可能入栈的为空void visit_rootfirst(node* root){ stack<node*> sta; bool _end = false; node* p ; sta.push(root); printf("%c",root->data); while(!sta.empty()) { p = sta.top(); while(p) { p = p->lchild; sta.push(p); if(p) { printf("%c",p->data); } } sta.pop(); p = sta.top(); // 左子树访问完,根节点退栈但不输出 sta.pop(); p = p->rchild; if(p) { sta.push(p); printf("%c",p->data); continue; } while( p == NULL) { if(sta.empty()) { _end = true; break; } p = sta.top(); sta.pop(); p = p->rchild; } if(!_end) { sta.push(p); printf("%c",p->data); } } return ;}int main(){ char* str = new char[100]; gets(str); //printf("%s",str); node* root = new node; buildtree(str,root); visit_rootfirst(root); return 0;}
阅读全文
0 0
- 先根遍历__非递归操作
- 中跟遍历__非递归操作
- 非递归先序遍历二叉树
- 数据结构(非递归先序遍历)
- 非递归先序遍历二叉树
- 先序遍历二叉树 [非递归]
- 先序遍历(非递归算法)
- 非递归先序遍历二叉树
- python 先序遍历非递归
- 二叉树非递归先序遍历
- 先序遍历的非递归算法
- 二叉树非递归先序遍历
- 非递归先序遍历二叉树
- 二叉树的先根遍历,中根遍历,后根遍历的非递归算法
- 试直接利用栈的基本操作写出先序遍历的非递归
- 二叉树的基本操作(非递归前中后遍历,先序,表达式建树,复制二叉树)
- 二叉树的先序递归以及非递归遍历
- 二叉树的先序递归,非递归遍历
- 64.笔记 MySQL学习——空间、布尔、NULL值
- keil uversion 的简单的使用
- 65.(转) MySQL数据类型
- 11.02~11.16大周总结。
- Keras:基于Python的深度学习库
- 先根遍历__非递归操作
- 66.笔记 MySQL学习——MySQL的BIT数据类型
- Matlab 2015b 激活失效后,重新激活
- Linux的命令
- Mybatis之对原生态JDBC程序中问题总结(1)
- Dijkstra算法与Floyd算法
- 水仙花数的java算法实现
- 我的第一个安卓应用出生过程及总结
- hdu