二叉树的非递归遍历

PTA | 程序设计类实验辅助教学平台 (pintia.cn)

#include <stdio.h>
#include <stdlib.h>
typedef enum { false, true } bool;

typedef char ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
    ElementType Data;
    BinTree Left;
    BinTree Right;
    int flag;
};

/*------堆栈的定义-------*/
typedef Position SElementType;
typedef struct SNode *PtrToSNode;
struct SNode {
    SElementType Data;
    PtrToSNode Next;
};
typedef PtrToSNode Stack;

/* 裁判实现,细节不表 */
Stack CreateStack();
bool IsEmpty( Stack S );
bool Push( Stack S, SElementType X );
SElementType Pop( Stack S ); /* 删除并仅返回S的栈顶元素 */
SElementType Peek( Stack S );/* 仅返回S的栈顶元素 */
/*----堆栈的定义结束-----*/

BinTree CreateBinTree(); /* 裁判实现,细节不表 */
void InorderTraversal( BinTree BT );
void PreorderTraversal( BinTree BT );
void PostorderTraversal( BinTree BT );

int main()
{
    BinTree BT = CreateBinTree();
    printf("Inorder:");    InorderTraversal(BT);    printf("\n");
    printf("Preorder:");   PreorderTraversal(BT);   printf("\n");
    printf("Postorder:");  PostorderTraversal(BT);  printf("\n");
    return 0;
}
/* 你的代码将被嵌在这里 */

 - -肯定有我民大同学抄,好小子,等下查重我们都G

//只能说我觉得这道题表述真不行
void InorderTraversal( BinTree BT ){//中序遍历
    BinTree T=BT;
    Stack S =CreateStack();
    while(T||!IsEmpty(S)){
        while(T!=NULL){
            Push(S,T);
            T=T->Left;
        }
        T=Pop(S);
        printf(" %c",T->Data);
        T=T->Right;
    }
}
void PreorderTraversal( BinTree BT ){//常规中序遍历
    BinTree T=BT;
    Stack S =CreateStack();
    while(T||!IsEmpty(S)){
        while(T!=NULL){
            Push(S,T);
            printf(" %c",T->Data);
            T=T->Left;
        }
        T=Pop(S);
        T=T->Right;
    }
}
void PostorderTraversal( BinTree BT ){
    BinTree T=BT;
    Stack S =CreateStack();
    while(T||!IsEmpty(S)){
        while(T!=NULL){
            T->flag=0;
            Push(S,T);//存入数据
            T=T->Left;//按照
        }
        T=Peek(S);//既然给了这个一定要用嘛,就跟着这个思路
        if(T->flag==0){
            T->flag++;//flag不为0,循环就退出了
            T=T->Right;
        }
        else{
            T=Pop(S);
            printf(" %c",T->Data);//那么复杂的操作,就是为了遍历的时候,记录好遍历的顺序的根节点
            T=NULL;
        }
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

name_name123

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

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

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

打赏作者

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

抵扣说明:

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

余额充值