linux学习总结(数据结构——树、二叉树以及遍历)

二叉树的存储:

顺序存储浪费空间。

二叉树链式存储结构:

typedef int datatype;

typedef struct node{

  datatype data;

struct node *lchild,*rchild;

}bitree,*root;

二叉树的遍历,由于二叉树的递归性质,遍历算法也是递归的。三种基本的遍历算法如下:

先访问树根,再访问左子树,最后访问右子树  先根遍历

先访问左子树,再访问树根,最后访问右子树 中根遍历

先访问左子树,再访问右子树,最后访问树根 后根遍历。

/********************
*二叉树
***********************/

#include <stdio.h>
#include <stdlib.h>

#define N  16
typedef struct _node_
{
    int no;
    struct _node_ *lchild, *rchild;
}bitree;

typedef bitree * datatype;
typedef struct 
{
    datatype data[N];
    int front, rear;
}sequeue;

sequeue *CreateEmptySequeue()
{
    sequeue *sq;

    sq = (sequeue*)malloc(sizeof(sequeue));
    sq->front = sq->rear = 0;

    return sq;
}

int EmptySequeue(sequeue *sq)
{
    return sq->front == sq->rear;
}

void EnSequeue(sequeue *sq, datatype x)
{
    sq->rear = (sq->rear + 1) % N;
    sq->data[sq->rear] = x;

    return;
}

datatype DeSequeue(sequeue *sq)
{
    sq->front = (sq->front + 1)%N;

    return sq->data[sq->front];
}

bitree *CreateBitree(int i, int n)
{
    bitree *root;

    root = (bitree *)malloc(sizeof(bitree));
    root->no = i;

    if(2*i <= n) root->lchild = CreateBitree(2*i, n);
    else  root->lchild = NULL;

    if(2*i+1 <= n) root->rchild = CreateBitree(2*i+1, n);
    else root->rchild = NULL;

    return root;
}
/***********遍历*************/
void PreOrder(bitree *root)
{
    if(root == NULL)    return;

    printf("%d ", root->no);
    PreOrder(root->lchild);
    PreOrder(root->rchild);

    return;
}

void InOrder(bitree *root)
{
    if(root == NULL)    return;

    InOrder(root->lchild);
    printf("%d ", root->no);
    InOrder(root->rchild);

    return;
}

void PostOrder(bitree *root)
{
    if(root == NULL)    return;

    PostOrder(root->lchild);
    PostOrder(root->rchild);
    printf("%d ", root->no);

    return;
}
/***********按层次遍历**************/
void NoOrder(bitree *root)
{
    sequeue *sq;

    sq = CreateEmptySequeue();
    EnSequeue(sq, root);

    while(!EmptySequeue(sq))
    {
        root = DeSequeue(sq);
        printf("%d ", root->no);

        if(root->lchild != NULL)
            EnSequeue(sq, root->lchild);
        if(root->rchild != NULL)
            EnSequeue(sq, root->rchild);
    }
    return;
}


int main()
{
    bitree *root;

    root = CreateBitree(1, 10);
    
    printf(" PreOrder:");
    PreOrder(root);
    printf("\n");

    printf("  InOrder:");
    InOrder(root);
    printf("\n");

    printf("PostOrder:");
    PostOrder(root);
    printf("\n");

    printf("  NoOrder:");
    NoOrder(root);
    printf("\n");


    return 0;
}

 

posted on 2012-06-14 22:02  孟浩依然  阅读(442)  评论(0编辑  收藏  举报