利用栈的中序遍历二叉树的非递归算法

来源:互联网 发布: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
原创粉丝点击