利用栈的中序遍历二叉树的非递归算法
来源:互联网 发布:vba提取网页数据 编辑:程序博客网 时间:2024/05/17 02:29
本文涉及四个方面的内容
1,树的遍历
2,栈的建立
3,树的中序遍历
4,相关函数的接口和参数
本文源码从上至下粘贴下来即可运行。
以下是相关头文件和结构体,包括树的结点和栈的结点
#include<stdio.h>#include<stdlib.h>#include<malloc.h>#define Max 100typedef struct bTree{ int data; struct bTree *lchild,*rchild;}bTree,*PbTree;typedef struct { bTree data[Max]; int top;}seqStack,*PseqStack;PseqStack initSeqStack(void); //结构体指针型函数 int isEmpty(PseqStack s); //判断栈内是否为空int pushStack(PseqStack s,bTree*x);//将树结点压入栈中int popStack(PseqStack s ,bTree **x);//从栈中弹出PbTree createTree(void);//(PbTree t);//中序遍历
以下是栈的初始化,压入,弹出。注意在栈的弹出栈的弹函数中二级指针的调用
PseqStack initSeqStack(void){ PseqStack s; s=(PseqStack)malloc(sizeof(seqStack)); s->top=-1; return s;}int isEmpty(PseqStack s){ if(s->top==-1) return 1; else return 0;}int pushStack(PseqStack s,bTree *x){ s->top++; s->data[s->top]=*x; return 1;}int popStack(PseqStack s ,bTree **x)//在函数中改变指针指向的内容需要使用二级指针{ *x=&s->data[s->top]; s->top--; return 1;}
以下是建立树和中序遍历算法
void inOrder(PbTree t)//中序遍历的非递归算法{ PseqStack s; PbTree p=t; s=initSeqStack(); while(p||!isEmpty(s)) { if(p) { pushStack(s,p);//将结点压入栈中 p=p->lchild; } else { popStack(s,&p); printf("%d",p->data); p=p->rchild; } }}PbTree createTree(void)//对结点进行赋值采用递归算法{ PbTree t; int x; printf("Input the root.\n"); scanf("%d",&x); if(x) { t=(PbTree)malloc(sizeof(bTree)); t->data=x; printf("Please input %d left child.\n",x); t->lchild=createTree(); printf("Please input %d right child.\n",x); t->rchild=createTree(); } else t=NULL; return t;}
最后是主函数
int main(){ PbTree t; t=createTree(); inOrder(t); return 0;}
0 0
- 利用栈的中序遍历二叉树的非递归算法
- 二叉树的中序遍历的非递归算法
- 中序遍历二叉树的非递归算法
- 二叉树的中序遍历(非递归算法)
- 二叉树遍历理解——递归及非递归方法中栈的利用
- 【LintCode-67】二叉树的中序遍历(Java实现-递归算法/非递归算法)
- 二叉树先序、中序、后序三种遍历的非递归算法
- 二叉树先序、中序、后序三种遍历的非递归算法
- 二叉树先序、中序、后序三种遍历的非递归算法
- 二叉树前序、中序、后序三种遍历的非递归算法
- 前,中,后序遍历二叉树 (递归 && 非递归的栈 && 非递归非栈的线索二叉树)
- 二叉树遍历的非递归算法
- 遍历二叉树的非递归算法
- 遍历二叉树的非递归算法
- 二叉树的遍历非递归算法
- 遍历二叉树的非递归算法
- 二叉树的遍历非递归算法
- 二叉树遍历的非递归算法
- 基本添加和遍历
- 反射(通过反射写一个通用的设置某个对象的某个属性为指定的值)
- 海量数据解决方案 知识总结
- C++ 基于CSock的远程五子棋对弈程序
- rhel7 install mysql
- 利用栈的中序遍历二叉树的非递归算法
- JAVA 中BIO,NIO,AIO的理解
- jQuery 删除、复制和替换元素
- 传统IO
- XMPP聊天之Openfire后台的安装和配置
- 初识ListView
- java 接口 抽象类 继承 重载 重写 多态
- 多态的成员(变量、方法)访问特点【非静态】
- #android#java的常用类