#include <stdio.h>
typedef
int
ElementType;
typedef
struct
TreeNode *Position;
typedef
struct
TreeNode *SearchTree;
struct
TreeNode
{
// 自身数据加上指向左右子树的指针
ElementType Element;
SearchTree Left;
SearchTree Right;
};
SearchTree MakeEmpty(SearchTree T)
{
if
(T != NULL)
{
MakeEmpty(T->Left);
MakeEmpty(T->Right);
free
(T);
}
return
T;
}
// 返回包含查找元素的指针或NULL
Position Find(SearchTree T, ElementType x)
{
if
(T == NULL)
return
NULL;
else
if
(T->Element < x)
return
Find(T->Right, x);
else
if
(T->Element > x)
return
Find(T->Left, x);
else
return
T;
}
Position FindMin(SearchTree T)
{
// 这个判断是必须的
if
(T != NULL)
while
(T->Left)
T = T->Left;
return
T;
}
// 递归版本
Position FindMin_recurse(SearchTree T)
{
if
(T == NULL)
return
NULL;
else
if
(T->Left == NULL)
return
T;
else
return
FindMin(T->Left);
}
Position FindMax(SearchTree T)
{
// 这个判断是必须的
if
(T != NULL)
while
(T->Right)
T = T->Right;
return
T;
}
// 相同节点已在树中,则不做任何操作
// 返回指向新树根的指针
SearchTree Insert(SearchTree T, ElementType x)
{
if
(T == NULL)
{
T =
malloc
(
sizeof
(
struct
TreeNode));
if
(T == NULL)
return
NULL;
T->Element = x;
T->Left = T->Right = NULL;
}
else
if
(x < T->Element)
T->Left = Insert(T->Left, x);
else
if
(x > T->Element)
T->Right = Insert(T->Right, x);
return
T;
}
SearchTree Delete(SearchTree T, ElementType x)
{
Position tmp;
if
(T == NULL)
return
NULL;
if
(x < T->Element)
T->Left = Delete(T->Left, x);
else
if
(x > T->Element)
T->Right = Delete(T->Right, x);
else
// 找到要删除的节点
{
if
(T->Left && T->Right)
// 该节点有两个儿子
{
tmp = FindMin(T->Right);
T->Element = tmp->Element;
T->Right = Delete(T->Right, tmp->Element);
}
else
// 有一个儿子或没有儿子
{
tmp = T;
if
(T->Left == NULL)
T = T->Right;
else
if
(T->Right == NULL)
T = T->Left;
free
(tmp);
}
}
return
T;
}
SearchTree CreateTree()
{
// 一定要初始化指针,因为Insert函数根据指针是否为空进行插入
SearchTree t = NULL;
return
t;
}
int
main()
{
SearchTree tree = CreateTree();
int
i;
for
(i = 0; i < 10; i++)
tree = Insert(tree, i);
printf
(
"Max = %d\n"
, FindMin(tree)->Element);
printf
(
"Max = %d\n"
, FindMax(tree)->Element);
return
0;
}
原文地址:http://blog.csdn.net/nestler/article/details/24720387