数据结构与算法分析——c语言描述 第四章树 二叉树
tree.h
typedef int ElementType;
#ifndef _Tree_H
#define _Tree_H
struct TreeNode;
typedef struct TreeNode *Position;
typedef struct TreeNode *SearchTree;
void makeEmpty(SearchTree t);
Position find(ElementType X, SearchTree t);
Position findMin(SearchTree t);
Position findMax(SearchTree t);
SearchTree insert(ElementType X, SearchTree t);
SearchTree Delete(ElementType X, SearchTree t);
ElementType Retrieve(Position p);
#endif
tree.c
#include"tree.h"
#include"fatal.h"
struct TreeNode {
ElementType element;
SearchTree left;
SearchTree right;
};
void makeEmpty(SearchTree t) {
if (t) {
makeEmpty(t->left);
makeEmpty(t->right);
free(t);
}
}
Position find(ElementType X, SearchTree t) {
if (t == NULL)
return NULL;//NOT FOUND
else {
if (X < t->element)
return find(X, t->left);
else if (X>t->element)
return find(X, t->right);
else
return t;
}
}
Position findMin(SearchTree t) {
while (t->left)
t = t->left;
return t;
}
Position findMax(SearchTree t)
{
while (t->right)
t = t->right;
return t;
}
SearchTree insert(ElementType X, SearchTree t) {
if (t == NULL) {//包含树没有初始化
t = malloc(sizeof(struct TreeNode));
if (t == NULL)
Error("out of memory");
t->element = X;
t->left = NULL;
t->right = NULL;
}
else {
if (X < t->element)
t->left = insert(X, t->left);
else if (X>t->element)
t->right = insert(X, t->right);
}
return t;//两种情况
}
SearchTree Delete(ElementType X, SearchTree t) {
Position tempCell;
if (t == NULL)
{
Error("Element not found");
}
else if (X < t->element)
t->left = Delete(X, t->left);
else if (X > t->element)
t->right = Delete(X, t->right);
else if (t->left && t->right)
{
tempCell = findMin(t->right);
t->element = tempCell->element;
t->right = Delete(t->element, t->right);
}
else
{
tempCell = t;
if (t->left == NULL)
t = t->right;
else if (t->right == NULL)
t = t->left;
free(tempCell);
}
return t;
}
ElementType Retrieve(Position p) {
return p->element;
}