c语言实现二叉树的建立以及二叉树的先序遍历和层次遍历源代码

c语言实现二叉树的建立以及二叉树的先序遍历和层次遍历源代码,第1张

#include
#include
#define MAXSIZE 100
typedef char datatype;
typedef struct node{
    datatype data;
    struct node*lchild;
    struct node*rchild;
}node;
typedef struct binarytree{
    node*root;
}binarytree;
binarytree* nulltree(binarytree*bt){
    bt->root=NULL;
    return bt;
}
binarytree* makebtree(binarytree* bt,datatype x,binarytree*ltree,binarytree*rtree){
    bt->root=(node*)malloc(sizeof(node));
    bt->root->data=x;
    bt->root->lchild=ltree->root;
    bt->root->rchild=rtree->root;
    return bt;
}
void preorder(node*root){
    if(root){
        printf("%c",root->data);
        preorder(root->lchild);
        preorder(root->rchild);
    }
}
void preoredertree(binarytree*bt){
    if(bt->root){
        preorder(bt->root);
        printf("\n");
    }
}
typedef struct qnode{
    int front;
    int rear;
    node*data[MAXSIZE];
}queue;
queue* create(queue*q){
    q=(qnode*)malloc(sizeof(qnode));
    q->front=q->rear=0;
}
queue* inselem(queue*q,node*btnode){
    if(q&&btnode){
        if((q->rear+1)%MAXSIZE!=q->front){
        int ret=(q->rear+1)%MAXSIZE;
        q->data[ret]=btnode;
        q->rear=(q->rear+1)%MAXSIZE;
        return q;
        }
        else
        printf("this queue is full\n");
    }
}
queue* deldata(queue*q){
    if(q){
        if(q->front!=q->rear){
            int ret=(q->front+1)%MAXSIZE;
            q->data[ret]=q->data[q->front];
            q->front=(q->front+1)%MAXSIZE;
            return q;
        }
        else
        printf("this queue is empty");
    }
    else
    printf("this queue is not exist\n");
}
bool isempty(queue*q){
    return q->front==q->rear;
}
node* front(queue*q){
    node*p;
    p=q->data[(q->front+1)%MAXSIZE];
    return p;
}
queue* destroy(queue*q){
    if(q){
        while(!isempty(q)){
            deldata(q);
        }
        free(q);
    }
}
void levelorder(binarytree*bt){
    if(bt){
        node*p;
        p=bt->root;
        queue*q;
        q=create(q);
        inselem(q,p);
        while(!isempty(q)){
              printf("%c",p->data);
              deldata(q);
              if(p->lchild)
              inselem(q,p->lchild);
              if(p->rchild)
              inselem(q,p->rchild);
              p=front(q);
        }
        destroy(q);
        printf("\n");
    }
}
int main(){
    binarytree bt1,bt2,bt3,bt4,bt5;
    nulltree(&bt5);
    makebtree(&bt2,'B',&bt5,&bt5);
    makebtree(&bt4,'D',&bt5,&bt5);
    makebtree(&bt3,'C',&bt4,&bt5);
    makebtree(&bt1,'A',&bt2,&bt3);
    preoredertree(&bt1);
    levelorder(&bt1);
    levelorder(&bt3);
    return 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/564861.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-06
下一篇 2022-04-06

发表评论

登录后才能评论

评论列表(0条)

保存