数据结构-3 二叉树的遍历

#include<stdio.h>
typedef int ElementType;
// 二叉树链式存储的数据结构
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode {
    ElementType Data;
    BinTree Left;
    BinTree Right;
};

// 前序遍历的递归实现
void PreorderTraversal1(BinTree BT) {
    if (BT) {
        printf("%d", BT->Data); 
        PreorderTraversal(BT->Left);
        PreorderTraversal(BT->Right);
    }
}

// 前序遍历的堆栈实现
void PreorderTraversal2(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 InorderTraversal1(BinTree BT) {
    if (BT) {
        PreorderTraversal(BT->Left);
        printf("%d", BT->Data); 
        PreorderTraversal(BT->Right);
    }
}

// 中序遍历的堆栈实现
void InorderTraversal2(BinTree BT) {
    BinTree T = BT;
    Stack S = CreateStack(MaxSize);
    while (T || !isEmpty(S)) {
        while (T) {
            Push(S, T);
            T = T->Left;
        }
        if (!isEmpty(S)) {
            T = Pop(S);
            printf("%d", T->Data);
            T = T->Right;
        }
    }
}

// 后序遍历的递归实现
void PostorderTraversal1(BinTree BT) {
    if (BT) {
        PreorderTraversal(BT->Left);
        PreorderTraversal(BT->Right);
        printf("%d", BT->Data); 
    }
}

// 后序遍历的堆栈实现

// 层次遍历的队列实现
void LevelorderTraversal(BinTree BT) {  
    BinTree TP;
    if (!BT)    return;
    Queue Q = CreateQueue();
    AddQuene(Q, BT);    // 将根节点入队
    while (isEmpty(Q)) {
        TP = DeleteQueue(Q);
        printf("%d ", TP->Data);
        if (TP->Left)   AddQuene(Q, TP->Left);
        if (TP->Right)  AddQuene(Q, TP->Right);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值