好久没有更新了。主要看高数了。专业课放了一放。最近又看了看二叉树,学到了很多以前没有注意到的细节。
#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;
}
接下来的时间会跟家努力。
祝大家考研成功。