【学习笔记】关于二叉树

来源:互联网 发布:java 获取系统字符集 编辑:程序博客网 时间:2024/06/02 17:47

这是以二叉链表为基础的学习记录

结点定义如下:

typedef struct node{    char date;    struct node *lc,*rc;} tree,*tr;


 

其中data只是表示数据域,应用是根据情况修改。*lc和*rc为左子树指针和右子树指针。

先序遍历函数,变量向上对应。

void xian(tr t){    if(t!=NULL)    {        printf("%c",t->data);        xian(t->lc);        xian(t->rc);    }}


 

中序遍历函数,变量向上对应。

 

void zhong(tr t){    if(t!=NULL)    {        zhong(t->lc);        printf("%c",t->data);        zhong(t->rc);    }}

后序遍历函数,变量向上对应。

 

void hou(tr t){    if(t!=NULL)    {        hou (t->lc);        hou(t->rc);        printf("%c",t->data);    }}


按层次遍历函数,变量向上对应。

void ceng (tr t){    int rear = 1,front = 0;    tree *p[52];    p[0] = t;    while(rear>front)    {        if(p[front])        {            printf("%c",p[front]->date);            p[rear] = p[front]->lc;            rear++;            p[rear] = p[front]->rc;            rear++;            front++;        }        else            front++;    }}


注释:通过一个指针数组来实现队列思想,也相当于最后依次输出指针数组指向的节点的数据域内容。

叶子节点计数函数。

 上文中count没有定义;为一全局变量,起计数作用,主函数可输出。

void leaf(tr t){    if(t!=NULL)    {        if(t->lc==NULL&&t->rc==NULL)        {            count++;        }        else        {            leaf(t->lc);            leaf(t->rc);        }    }}


二叉树深度计算函数,说是计算,实际上就是找返回值最大的。

int deep (tr t){    if(t!=NULL)    {        int a = deep(t->lc),b = deep(t->rc);        if(a>b)        {            return a+1;        }        else        {            return b+1;        }    }    else    {        return 0;    }    return 0;}


最终返回值就是深度。

原创粉丝点击