二叉树的非递归遍历前中后序和层次遍历

#include<stdio.h>
#include<stack.c>
#include<stdbool.h>
#include<SquenceNode.c>

#define MaxSize 20


typedef struct TreeNode *BinTree;
typedef BinTree Position;
typedef int ElementType;

//二叉树的链式存储结构
struct TreeNode
{
    ElementType Data;
    BinTree Left;
    BinTree Right;
    BinTree IsFirst;//用于标志是否是第一次进栈 
};

/**
 * 二叉树的中序遍历(非递归)
 * */
void InorderTraversal( BinTree BT)
{
    BinTree T = BT;
    Stack S = CreateStack(MaxSize);
    while( T || !isEmpty( S ) )
    {
        while( T )
        {
            T->IsFirst = true;
            //一直向左并将沿途的结点压入堆栈
            Push(S,T);
            T = T->Left;
        }

        if(!isEmpty(S))
        {
            //左子树遍历完了,该弹出栈顶结点
            T = Pop(S);
            printf("%d", T->Data);
            //左子树输出完了,转向右子树
            T = T->Right;
        }
    }
}

/**
 * 先序遍历的非递归遍历算法
 * */
void PreOrderTraversal( BinTree BT)
{
    BinTree T = BT;
    Stack S = CreateStack(MaxSize);
    while( T || !isEmpty( S ) )
    {
        while( T )
        {
            //一直向左并将沿途的结点压入堆栈
            Push(S,T);
            //第一次遇到这个结点就输出
            printf("%d", T->Data);
            T = T->Left;
        }

        if(!isEmpty(S))
        {
            //左子树遍历完了,该弹出栈顶结点
            T = Pop(S);
            //左子树输出完了,转向右子树
            T = T->Right;
        }
    }
} 

/**
 * 后序遍历的非递归遍历算法
 * */
void PostOrderTraversal( BinTree BT)
{
    BinTree T = BT;
    Stack S = CreateStack(MaxSize);
    while( T || !isEmpty( S ) )
    {
        while( T )
        {
            T->IsFirst = true;//标记为第一次进栈
            //一直向左并将沿途的结点压入堆栈
            Push(S,T);
            T = T->Left;
        }

        if(!isEmpty(S))
        {
            //左子树遍历完了,该弹出栈顶结点
            T = Pop(S);
            if(T->IsFirst == true)
            {
                T->IsFirst = false;
                Push(S,T);
                T = T->Right;
            }
            else
            {
                printf("%d", T->Data);
                T = NULL;
            }
        }
    }
} 

/**
 * 层次遍历
 * */
void LevelOrderTraversal( BinTree BT)
{
    Queue Q;
    BinTree T;
    if( !BT ) return;
    Q = CreateQueue( MaxSize );
    Add(Q, BT);
    while( ! isEmpty(Q) )
    {
        T = Delete(Q);
        printf("%d\n", T->Data);
        if(T->Left)
            Add(Q, T->Left);
        if(T->Right)
            Add(Q, T->Right);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刘璐菲

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值