二叉树的递归和非递归遍历

递归遍历

先序遍历

void PreorderTraversal( BinTree BT )
{
    if(BT == NULL) return;
    printf(" %c", BT->Data);
    PreorderTraversal(BT->Left);
    PreorderTraversal(BT->Right);
}

中序遍历

void InorderTraversal( BinTree BT )
{
    if(BT == NULL) return;
    InorderTraversal(BT->Left);
    printf(" %c", BT->Data);
    InorderTraversal(BT->Right);

}

后序遍历

void PostorderTraversal( BinTree BT )
{
    if(BT == NULL) return;
    PostorderTraversal(BT->Left);
    PostorderTraversal(BT->Right);
    printf(" %c", BT->Data);

}

非递归遍历

先序遍历

void PreorderTraversal( BinTree BT )
{
    BinTree t;
    Stack s = CreateStack();
    t = BT;
    while (t || !IsEmpty(s))
    {
        while (t)
        {
            Push(s, t);
            printf(" %c", t->Data);
            t = t->Left;
        }
        t = Pop(s);
        t = t->Right;
    }
}

中序遍历

void InorderTraversal( BinTree BT )
{
    BinTree t;
    Stack s = CreateStack();
    t = BT;
    while (t || !IsEmpty(s))
    {
        while (t)
        {
            Push(s, t);
            t = t->Left;
        }
        t = Pop(s);
        printf(" %c", t->Data);
        t = t->Right;
    }
}

后序遍历

void PostorderTraversal( BinTree BT )
{
    BinTree t;
    Stack s = CreateStack();
    t = BT;
    while (t || !IsEmpty(s))
    {
        while (t)
        {
            Push(s, t);
            t->flag = 1;
            t = t->Left;
        }
        t = Pop(s);
        if(t->flag == 1)
        {
            Push(s, t);
            t->flag = 2;
            t = t->Right;
        }
        else
        {
            printf(" %c", t->Data);
            t = NULL;
        }
    }
}

层次遍历

借助数组模拟队列的先进先出

void LevelorderTraversal( BinTree BT )
{

    if(BT == NULL) return;
    BinTree queue[10000];
    int left = 0, right = 0;
    queue[right++] = BT;
    while (left < right)
    {
        BinTree t = queue[left++];
        printf(" %c", t->Data);
        if (t->Left) queue[right++] = t->Left;
        if (t->Right) queue[right++] = t->Right;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值