考研党 《数据结构(C语言版)》 严蔚敏BiTree基本操作

好久没有更新了。主要看高数了。专业课放了一放。最近又看了看二叉树,学到了很多以前没有注意到的细节。

#ifndef _BITREE_H_ 
#define _BITREE_H_

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

#define OK 1
#define ERROR 0

typedef char ElemType;
typedef int Status;

typedef struct SNode
{
    ElemType data;
    struct SNode* lChild;
    struct SNode* rChild;
} Node,*BiTree;

Node* InitNode(ElemType data)
{
    Node* node = (Node*) malloc ( sizeof(Node) );
    node->data = data;
    node->lChild = NULL;
    node->rChild = NULL;
}
void inputData( ElemType *e)
{
    scanf( "%c", e);
}

Status CreateBiTree( BiTree *T, int i)
{
    ElemType e;
    inputData(&e);
    if ( '.'!= e )
    {
        (*T) = InitNode(e);
        printf("node %c in %d floor\n", e ,++i);
        CreateBiTree( &((*T)->lChild) ,i);
        CreateBiTree( &((*T)->rChild) ,i);
    }
}
void visit( ElemType data)
{
    printf("%c ", data);
}
Status PreVisit( BiTree T)
{
    if ( T )
    {
        visit( T->data );
        PreVisit( T->lChild );
        PreVisit( T->rChild );
    }
    return OK;
}

Status AfterVisit( BiTree T)
{
    if ( T )
    {
        AfterVisit( T->lChild );
        AfterVisit( T->rChild );
        visit( T->data );
    }
    return OK;
}

Status MidVisit( BiTree T)
{
    if ( T )
    {
        MidVisit( T->lChild );
        visit( T->data );
        MidVisit( T->rChild );
    }
    return OK;
}
Status PreOrderVisit( BiTree T)
{
    PreVisit(T);
    printf( "\n" );
}
Status MidOrderVisit( BiTree T)
{
    MidVisit(T);
    printf( "\n" );
}

Status AfterOrderVisit( BiTree T)
{
    AfterVisit(T);
    printf( "\n" );
}
void FreeTree( BiTree* T)
{
    if ( *T )
    {
        FreeTree( &(*T)->lChild );
        FreeTree( &(*T)->rChild );
        free(*T);
        *T = NULL; 
    }
}
int getDepth( BiTree T)
{
    if ( T )
    {
        int depl = getDepth( T->lChild );
        int depr = getDepth( T->rChild );
        return 1 + ( depl>depr ? depl:depr );
    }
    return 0;

}

int getLeafNumber( BiTree T)
{
    if ( T )
    {
        if ( !T->lChild && !T->rChild )
        {
            return 1;
        }
        return getLeafNumber( T->lChild ) + getLeafNumber( T->rChild );
    }
    return 0;
}
#endif

上面的代码段是BiTree.h 主要用来创建以及遍历销毁二叉树。

#include "BiTree.h"
int main(int argc, char const *argv[])
{
    /*
    test data:
    12..3..
    */
    BiTree T = NULL; 
    CreateBiTree( &T ,0);
    printf("Create BiTree Success!\n");

    PreOrderVisit( T );
    MidOrderVisit( T );
    AfterOrderVisit( T );

    printf("Depth = %d\n", getDepth( T ) );
    printf("SumLeaf = %d\n", getLeafNumber( T ));

    FreeTree( &T );
    return 0;
}

这里写图片描述
接下来的时间会跟家努力。
祝大家考研成功。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值