数据结构——二叉树

来源:互联网 发布:c语言贪吃蛇源代码 编辑:程序博客网 时间:2024/05/20 22:41

二叉树前序,中序,后序,按层遍历:



#include <stdio.h>

#include <stdlib.h>

#include<iostream>

#include<queue>

using namespace std;


#define N 100


char *a="ABC##D#E##F##";    //扩充二叉树t的前序序列


typedef struct node//二叉树结构定义

{

    char data;

    struct node *lchild,*rchild;

}binnode;


typedef binnode *bintree;


//函数creatbintree (根据扩充二叉树的前序序列(字符串a)建立二叉树t的存储结构

bintree  creatbintree()

{

    char ch=*a++;

    bintree t;

    if  (ch=='#')  t=NULL;

    else

    {

        t=(bintree)malloc(sizeof(binnode));

        t->data=ch;

        t->lchild=creatbintree();

        t->rchild=creatbintree();

    }

    return t;

}


void preorder(bintree t) //前序递归遍历二叉树

{

    if (t)

    {

        printf("%c",t->data);

        preorder(t->lchild);

        preorder(t->rchild);

    }

}

void inorder(bintree t) //中序递归遍历二叉树

{

    if (t)

    {

        

        inorder(t->lchild);

        printf("%c",t->data);

        inorder(t->rchild);

    }

}

void postorder(bintree t)//后序递归遍历二叉树

{

    if (t)

    {

        postorder(t->lchild);

        postorder(t->rchild);

        printf("%c",t->data);

    }

}


void levelorder(bintree t) //按层遍历二叉树

{

    queue<bintree>que;

    que.push(t);

    while(!que.empty())

    {

        bintree now=que.front();

        que.pop();

        cout<<now->data;

        if(now->lchild)

        {

            que.push(now->lchild);

        }

        if(now->rchild)

        {

            que.push(now->rchild);

        }

    }

}


int main()

{

    bintree t;

    t=creatbintree(); //建立二叉树t的存储结构

    printf("二叉树的前序序列为:\n");

    preorder(t);

    printf("\n");

    printf("二叉树的中序序列为:\n");

    inorder(t);

    printf("\n");

    printf("二叉树的后序序列为:\n");

    postorder(t);

    printf("\n");

    printf("二叉树的按层遍历为:\n");

    levelorder(t);

    printf("\n");

    return 0;

}


原创粉丝点击