非递归前序周游二叉树

  • 主要思想:
    每遇到一个结点,先访问该结点,并把该结点的非空右子结点推入栈中,然后周游其左子树;
    左子树周游不下去时,从栈顶弹出待访问的结点,继续周游。
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define OK 1
#define ERROR 0
#define MAXSIZE 20


typedef char TElemType;
typedef int Status;

typedef struct BiTNode  //二叉树的链式存储结构
{
    TElemType data;
    struct BiTNode * lchild;
    struct BiTNode * rchild; 
}BiTnode,*BiTree;

typedef BiTree SElemType;
typedef struct      //顺序栈的储存结构
{
    SElemType data[MAXSIZE];
    int top;    //用于栈顶指针
}Sqstack;



//顺序栈的初始化
Status InitSqstack(Sqstack * S)
{
    S->top=-1;
    return OK;
}

//出栈操作
Status Pop(Sqstack * S,SElemType * e)
{
    if(S->top==-1)  //栈底
    {
        return ERROR;
    }
    *e=S->data[S->top];
    S->top--;
    return OK;
}


//进栈操作
Status Push(Sqstack * S,SElemType e)
{
    if(S->top==MAXSIZE-1)   //栈满
    {
        return ERROR;
    }
    S->top++;   //栈顶指针增加1
    S->data[S->top]=e;
    return OK;
}



void CreateBiTree(BiTree * T)   //二叉树的建立
{
    TElemType ch;
    scanf("%c",&ch);
    if(ch=='#')
    {
        *T=NULL;
    }
    else
    {
        (*T)=(BiTree)malloc(sizeof(BiTNode));
    }
    if(!(*T))
    {
        return ;
    }
    else
    {
        (*T)->data=ch;
        CreateBiTree(&(*T)->lchild);
        CreateBiTree(&(*T)->rchild);
    }
}

//非递归前序周游二叉树
void PerOrderWithoutRecursion(BiTree * T,Sqstack * S)
{
    if(!(*T))
    {
        printf("空树!\n");
        return ;
    }
    while((*T)!=NULL || S->top!=-1)
    {
        while((*T))
        {
            if((*T)->rchild!=NULL)
            {
                Push(S,(*T)->rchild);
            }
            printf("%c ",(*T)->data);
            (*T)=(*T)->lchild;
        }
            Pop(S,&(*T));
    }
    printf("\n");
}


int main()
{
    BiTree  root;
    Sqstack S;
    InitSqstack(&S);
    printf("Enter the data :\n");
    CreateBiTree(&root);
    printf("PerOrderWithoutRecursion the data:\n");
    PerOrderWithoutRecursion(&root,&S);
    return 0;
}

“`运行结果

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值