【数据结构】二叉树

点击查看代码
#include <stdio.h>
#include <stdlib.h>
typedef char dataType;

typedef struct node{

    dataType data;
    struct node *lchild,*rchild;

}BinTree;
/*---创建二叉树---*/
BinTree *CreateBinTree()
{/*先序建立一个二叉树链表*/
    BinTree *bt = NULL;
    char ch;

    ch = getchar();

    if(ch!='#')
    {
        bt = (BinTree *)malloc(sizeof(BinTree));
        bt->data = ch;
        bt->lchild = CreateBinTree();
        bt->rchild = CreateBinTree();

    }
    return bt;

}
void  endprintfBinTree(BinTree *bt)
{
    if(bt != NULL)
    {/*---后序二叉树遍历---*/
        
        printfBinTree(bt->lchild);
        printfBinTree(bt->rchild);
        printf("%c",bt->data);
    }

}
void  firstprintfBinTree(BinTree *bt)
{
    if(bt != NULL)
    {/*---先序二叉树遍历---*/
        printf("%c",bt->data);
        printfBinTree(bt->lchild);
        printfBinTree(bt->rchild);
    }

}
void  middelprintfBinTree(BinTree *bt)
{
    if(bt != NULL)
    {/*---中序二叉树遍历---*/
        
        printfBinTree(bt->lchild);
        printf("%c",bt->data);
        printfBinTree(bt->rchild);
    }

}


/*---按中序遍历的方法求叶子节点的总数---*/
void CountLeaf(BinTree *t,int* count)
{
    if(t)
    {
        if(!(t->lchild)&&!(t->rchild))
        {
            (*count)++;
            CountLeaf(t->lchild,count);
            CountLeaf(t->rchild,count);
        }
        
    }
}
/*---求二叉树深度---*/
int  Depth(BinTree *t)
{
    int h1,hr;
    if(!t) return 0;
    else
    {
        h1 = Depth(t->lchild);
        hr = Depth(t->rchild);
        if(h1>=hr) return h1+1;
        else
            hr+1;
        
    }
}

int main()
{
    BinTree *bt;

   bt =  CreateBinTree();
    firstprintfBinTree(bt);
    middelprintfBinTree(bt);
    endprintfBinTree(bt);
    
    



}

上一篇:[C语言]二叉搜索树


下一篇:福报厂面试之树的遍历、节点统计、树高计算