中序非递归遍历二叉树

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39984761/article/details/78645567

二叉树的递归算法虽然简单,但是会导致时间复杂度比较高,下面给大家带来用栈实现的二叉树非递归算法

首先定义好二叉树,和元素类型为二叉树的栈

typedef struct BiTNode{
    TElemType    data;
    struct BiTNode *lchild, *rchild;
}BiTNode,*BiTree;

typedef BiTree SElemType;
typedef struct{
    SElemType *base;
    SElemType *top;
    int stacksize;
}SqStack;


然后实现栈的方法

#include"1.h"

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
using namespace std;

//初始化栈
Status InitStack(SqStack &s){
    s.base=(SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
    if(!s.base)exit(OVERFLOW);
    s.top=s.base;
    s.stacksize=STACK_INIT_SIZE;
    return OK;

}
//取栈顶元素
Status GetTop(SqStack s,SElemType &e){
    if(s.top=s.base)
    return ERROR;
    e=*(s.top-1);
    return OK;
}

//元素入栈
Status Push(SqStack &s,SElemType e){
    if(s.top-s.base>=s.stacksize){
        s.base=(SElemType *)realloc(s.base,(s.stacksize+STACKINCREMENT)*sizeof(SElemType));
        if(!s.base)exit(OVERFLOW);
        s.top=s.base+s.stacksize;
        s.stacksize+=STACKINCREMENT;
    }
    *s.top++ =e;
    return OK;

}

//取栈顶元素,并使top指针下移(也就是出栈)
Status Pop(SqStack &s,SElemType &e){
    if(s.top==s.base)return ERROR;
    e=*--s.top;
    return OK;
}

//判断栈是否
Status StackEmpty(SqStack &s){
    if(s.top==s.base)return TURE;
    else 
    return FALSE;
}

然后通过栈的操作遍历二叉树

Status InOrderTraverse(BiTree T){
    SqStack sta;
    BiTree point;
    InitStack(sta);point=T;
    while(point||!StackEmpty(sta)){
        if(point){Push(sta,point);point=point->lchild;}
        else{
            Pop(sta,point);if(!Visit(point->data))return ERROR;
            point=point->rchild;

        }
    }
    return OK;
}

这样方法就写好了,想再检验一下方法可以在主函数中调用


#include <iostream>
#include"head2.h"
using namespace std;


int main() {
BiTNode *BiTree;
    if(CreateBiTree(BiTree))
        cout<<"建树成功";
    else{
    }
    cout<<"\n中序非递归遍历二叉树";
    if(InOrderTraverse(BiTree))
        cout<<"遍历成功";
    else{}
        system("pause");
}

猜你喜欢

转载自blog.csdn.net/qq_39984761/article/details/78645567