二叉树相关操作

来源:互联网 发布:tigervnc windows 编辑:程序博客网 时间:2024/04/25 03:36

#include <stdio.h>

#include <malloc.h>

 

struct node    //节点的数据结构

{

    int data;

    struct node *left;

    struct node *right;

};

--- --- --- --- --- ---  前 序 遍 历  --- --- --- --- --- ---

void PreOrder(struct node * p) 

{

    if (p)

    {

        printf(" %d ",(*p).data);

        PreOrder((*p).left);

        PreOrder((*p).right);

    }

}

--- --- --- --- --- ---  中 序 遍 历  --- --- --- --- --- ---

void InOrder(struct node * p) 

{

    if (p)

    {

        InOrder((*p).left);

        printf(" %d ",(*p).data);      

        InOrder((*p).right);

    }

}

--- --- --- --- --- ---  后 序 遍 历  --- --- --- --- --- ---

void PostOrder(struct node * p) 

{

    if (p)

    {

        PostOrder((*p).left);              

        PostOrder((*p).right);

        printf(" %d ",(*p).data);

    }

}

--- --- --- --- --- ---  逐 层 遍 历  --- --- --- --- --- ---

void LevelOrder(struct node * p) 

//队列的初始化、插入、删除代码略

{

    struct node * q = InitQueue(); //初始化一个队列

    while(p)

    {

        printf(" %d ",(*p).data);

        if((*p).left) QueueAdd(q,(*p).left); //左子放入队列

        if((*p).right) QueueAdd(q,(*p).right); //右子放入队列

        p = QueueDelete(q);  //从队列中删除

    }

}

--- --- --- --- ---  计 算 二 叉 树 高 度  --- --- --- --- ---

int TreeHeight(struct node * p)

{

    int hl,hr;

    if(!p) return 0;

    hl = TreeHeight((*p).left); //左子树高度

    hr = TreeHeight((*p).right); //右子树高度

    if(hl > hr) return ++hl;

    else return ++hr;

}

--- --- --- --- --  二叉树链表转数组(递归)  --- --- --- --- --

void ChainTreeToArray(struct node * p,int a[],int i)

{

    if (p)

    {

        a[i] = (*p).data;

        ChainTreeToArray((*p).left,a,2*i);

        ChainTreeToArray((*p).right,a,2*i+1);

    }

}

--- --- --- --- --  二叉树数组转链表(递归)  --- --- --- --- --

struct node * ArrayTreeToChain(int a[],int n,int i)

{

    struct node * p;

    if(n<1 || i>n || a[i]==0/*假设0表示空值*/) return 0;

    p = (struct node *)malloc(sizeof(struct node));

    (*p).data = a[i];

    (*p).left = ArrayTreeToChain(a,n,2*i);

    (*p).right = ArrayTreeToChain(a,n,2*i+1);

    return p;

}

 

--- --- --- --- --- --- --- 调 用 --- --- --- --- --- --- ---

void main()

{

    struct node a,b,c,d,e,*root,*r;

    int i,k[7] = {0};   //假设0表示空值

    a.data = 1; a.left = &b; a.right = &c;

    b.data = 2; b.left = 0;  b.right = &d;

    c.data = 3; c.left = &e; c.right = 0;

    d.data = 4; d.left = 0;  d.right = 0;

    e.data = 5; e.left = 0;  e.right = 0;  

    root = &a;

 

    PreOrder(root); 

    InOrder(root); 

    PostOrder(root); 

    ChainTreeToArray(root,k,1);

    r = ArrayTreeToChain(k,6,1);

}

原创粉丝点击