非递归遍历二叉树
来源:互联网 发布:淘宝海外直邮可信吗 编辑:程序博客网 时间:2024/05/30 23:37
void preTraval(Node *head) {if (head == NULL)return;stack<Node *> st;st.push(head);while (!st.empty() ) {Node *t = st.top();st.pop();while (t) {//一边顺着左路走,一边遍历,并把右孩子放入栈中visit(t);if (t->right)st.push(t->right);t = t->left;}}}void inTraval(Node *head) {if (head == NULL)return;Node * t = head;stack<Node *> st;while (t !=NULL || !st.empty()) {while (t != NULL) {//顺着左路走,并把节点放入栈中st.push(t);t = t->left;}if (!st.empty()) {//走到左路的头之后,取栈中的节点,向右拐t = st.top();st.pop();visit(t);t = t->right;}}}
后序比较复杂
#define maxsize 100typedef enum{L,R} tagtype;typedef struct { Bitree ptr; tagtype tag;}stacknode;typedef struct{ stacknode Elem[maxsize]; int top;}SqStack;void PostOrderUnrec(Bitree t){ SqStack s; stacknode x; StackInit(s); p=t; do { while (p!=null) //遍历左子树 { x.ptr = p; x.tag = L; //标记为左子树,开始遍历其左子树 push(s,x); p=p->lchild; } while (!StackEmpty(s) && s.Elem[s.top].tag==R) { x = pop(s); p = x.ptr; visite(p->data); //tag为R,表示右子树访问完毕,故访问根结点 } if (!StackEmpty(s)) { s.Elem[s.top].tag =R; //遍历右子树;左子树到头了,所以要开始遍历右子树 p=s.Elem[s.top].ptr->rchild; } }while (!StackEmpty(s));}//PostOrderUnrec
struct Node { int data; Node *left; Node *right;};struct PostNode { Node *node; int type;//0 左;1 右};void post(Node *root) { stack<PostNode> st; Node *t = root; do { while(t!=NULL) { PostNode pn; pn->node = t; pn.type = 0; st.push(pn); t = t->left; } while(!st.empty() && st.top().type == 1) { cout<<st.top().node->data<<endl; st.pop(); } if (!st.empty()) { st.top().type = 1; t = st.top().node->right; } } while (!st.empty());}
- 非递归遍历二叉树
- 二叉树遍历非递归
- 非递归遍历二叉树
- 二叉树非递归遍历
- 二叉树非递归遍历
- 非递归遍历二叉树
- 二叉树非递归遍历
- 非递归遍历二叉树
- 非递归遍历二叉树
- 非递归遍历二叉树
- 非递归遍历二叉树
- 非递归遍历二叉树
- 二叉树非递归遍历
- 二叉树遍历--非递归
- 二叉树非递归遍历
- 非递归遍历二叉树
- 二叉树非递归遍历
- 二叉树非递归遍历
- MicroSoft 12个球一个天平,现知道只有一个和其它的重量不同,问怎样称才能用三次就找到那个球?那13个呢?
- DB2 递归调用
- 基于标志的AR介绍
- 从Trie树(字典树)谈到后缀树
- TCP三次握手过程
- 非递归遍历二叉树
- PCS/MES/ERP各层内容
- 线性表逆置
- Http Client 4.0 以POST方式提交数据
- 研究生学习计划
- c语言学习笔记十三
- Python进阶(一)——安装Python、程序执行、Python模块和IDLE调试
- iOS计算文字高度
- 做项目还是搞ACM?——浮躁的大学生活 by karottc