说明:
运行环境:linux
书籍:《数据结构与算法分析》
1.binary tree is an tree only 1 or 2 child
2.binary search tree left child < Elem < right child
BSTree.h
/**
** 1.binary tree is an tree only 1 or 2 child
** 2.binary search tree left child < Elem < right child
**
** @liulang datuhao@foxmail.com 2015-3-11
**/
#ifndef __BSTREE_H__
#define __BSTREE_H__
struct TreeNode;
typedef struct TreeNode *Position;
typedef struct TreeNode *SearchTree;
struct TreeNode
{
int Elem;
SearchTree Left;
SearchTree Right;
};
SearchTree MakeEmpty(SearchTree T);
Position Find(int Elem, SearchTree T);
Position FindMax(SearchTree T);
Position FindMin(SearchTree T);
Position Insert(int Elem, SearchTree T);
Position Delete(int Elem, SearchTree T);
#endif
BSTree.cpp
/**
** 1.binary tree is an tree only 1 or 2 child
** 2.binary search tree left child < Elem < right child
**
** @liulang datuhao@foxmail.com 2015-3-11
**/
#include <stdio.h>
#include <stdlib.h>
#include "BSTree.h"
SearchTree MakeEmpty(SearchTree T)
{
if(T != NULL)
{
MakeEmpty(T->Left);
MakeEmpty(T->Right);
free(T);
}
return NULL;
}
Position Find(int Elem, SearchTree T)
{
if(T == NULL)
{
printf("T is NULL\n");
return NULL;
}
//***for debug
printf("%d\n", T->Elem);
if(Elem < T->Elem)
{
if(T->Left == NULL)
{
printf("file:%s, line:%d T->Left = NULL error!\n",
__FILE__, __LINE__);
return NULL;
}
return Find(Elem, T->Left);
}
else if(Elem > T->Elem)
{
if(T->Right == NULL)
{
printf("file:%s, line:%d T->Right = NULL error!\n",
__FILE__, __LINE__);
return NULL;
}
return Find(Elem, T->Right);
}
else
{
printf("%d found!\n", T->Elem);
return T;
}
}
Position FindMax(SearchTree T)
{
/**
我没有判断的
**/
if(T==NULL)
{
return T;
}
if(T->Right != NULL)
{
return FindMax(T->Right);
}
else
{
return T;
}
}
Position FindMin(SearchTree T)
{
if(T == NULL)
{
return T;
}
else
{
while(T->Left)
{
T = T->Left;
}
}
return T;
}
Position Insert(int Elem, SearchTree T)
{
if(T == NULL)
{
T = (SearchTree)malloc(sizeof(struct TreeNode));
if(T== NULL)
{
printf("file:%s, line:%d error!\n", __FILE__, __LINE__);
return NULL;
}
T->Elem = Elem;
T->Left = NULL;
T->Right = NULL;
printf("%d have Insert!\n", T->Elem);
}
else
{
if(Elem < T->Elem)
{
T->Left = Insert(Elem, T->Left);
}
else if(Elem > T->Elem)
{
T->Right = Insert(Elem, T->Right);
}
else
{
printf("Elem is arleady exist!\n");
}
}
return T;
}
Position Delete(int Elem, SearchTree T);
</pre><p></p><p></p><p><strong><span style="color:#ff0000;"><em>main.cpp</em></span></strong></p><pre name="code" class="cpp">#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "BSTree.h"
int main(void)
{
int a;
SearchTree T = NULL;
SearchTree S = NULL;
T = MakeEmpty(T);
int i=0;
srand(time(NULL));
for(;i<1000; i++)
{
T = Insert(rand()%1000, T);
}
printf("the number you find:\n");
scanf("%d", &a);
printf("\n\n");
Find(a,T);
S = FindMax(T);
printf("the max elem is %d\n", S->Elem);
S = FindMin(T);
printf("the min elem is %d\n", S->Elem);
return 0;
}