二叉树的前序,中序,后序以及层次遍历

#include<iostream>

using namespace std;

 

typedef int elemtype;

 

#define Maxsize 50

 

typedef struct BiTNode {

    elemtype data;

    struct BiTNode *lchild,*rchild;

} BiTNode,*BiTree;

 

typedef struct Queue { //构造树节点队列

    BiTree tree[Maxsize];

    int front=0,rear=0;

} Queue;

 

bool QueueEmpty(Queue q) {//判断队空

    if(q.rear==q.front)

        return true;

    else

        return false;

}

 

bool QueueFull(Queue q) { //判断队满

    if((q.rear+1)%Maxsize==q.front)

        return true;

    else

        return false;

}

 

bool InQueue(Queue &q,BiTree b) { //入队

    if(QueueFull(q))

        return false;

    q.tree[q.rear]=b;

    q.rear=(q.rear+1)%Maxsize;

    return true;

}

 

bool OutQueue(Queue &q,BiTree &b) { //出队

    if(QueueEmpty(q))

        return false;

    b=q.tree[q.front];

    q.front=(q.front+1)%Maxsize;

    return true;

}

 

void InitBiTree(BiTree &b) {//构造二叉树

    b=(BiTree)malloc(sizeof(BiTNode));

    b->lchild=NULL;

    b->rchild=NULL;

}

 

void Insertlchild(BiTree &b,BiTree s) { //插入左子树

    if(b!=NULL)

        b->lchild=s;

}

 

void Insertrchild(BiTree &b,BiTree s) { //插入右子树

    if(b!=NULL)

        b->rchild=s;

}

 

void visit(BiTree b) {

    cout << b->data << endl;

}

 

void PreOrder(BiTree b) {//先序遍历

    if(b!=NULL) {

        visit(b);

        PreOrder(b->lchild);

        PreOrder(b->rchild);

    }

}

 

void InOrder(BiTree b) {//中序遍历

    if(b!=NULL) {

        InOrder(b->lchild);

        visit(b);

        InOrder(b->rchild);

    }

}

 

void PostOrder(BiTree b) {//后序遍历

    if(b!=NULL) {

        PostOrder(b->lchild);

        PostOrder(b->rchild);

        visit(b);

    }

}

 

void LayerOrder(BiTree b) { //层次遍历

    Queue q;

    InQueue(q,b);

    BiTree s;

    while(!QueueEmpty(q)) {

        OutQueue(q,s);

        visit(s);

        if(s->lchild!=NULL)

            InQueue(q,s->lchild);

        if(s->rchild!=NULL)

            InQueue(q,s->rchild);

    }

}

 

int treeDepth(BiTree b) {//求树的深度

    if(b==NULL)

        return 0;

    int l=treeDepth(b->lchild);

    int r=treeDepth(b->rchild);

    return l>r?l+1:r+1;

}

 

int main()

{

    BiTree root;

    InitBiTree(root);

    root->data=1;

    for(int j=2; j<4; j++) {

        BiTree s;

        InitBiTree(s);

        s->data=j;

        if(j%2==0)

            Insertlchild(root,s);

        else

            Insertrchild(root,s);

    }

    cout << "先序" << endl;

    PreOrder(root);

    cout << "中序" << endl;

    InOrder(root);

    cout << "后序" << endl;

    PostOrder(root);

    cout << "层次" << endl;

    LayerOrder(root);

    cout << "树深" << endl;

    cout << treeDepth(root) << endl;

    return 0;

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值