用C风格写的代码,可能用模块写更有利于应用。不过在C++里有map,set之类的容器,也不愿再去折腾了。
#ifndef __BINARY_SEARCH_TREE_H
#define __BINARY_SEARCH_TREE_H
#include
namespace dskit
{ typedef int ELEMENTSTYPE;
typedef struct BSTNode
{
ELEMENTSTYPE value;
struct BSTNode* left;
struct BSTNode* right;
}BSTNODE;
typedef BSTNODE* binary_search_tree;
binary_search_tree Insert(ELEMENTSTYPE x, binary_search_tree& bstTree);
binary_search_tree Delete(ELEMENTSTYPE x, binary_search_tree bstTree);
BSTNODE* Find(ELEMENTSTYPE x, binary_search_tree bstTree);
}
#endif
#include "binary_search_tree.h"
namespace dskit{
binary_search_tree Insert(ELEMENTSTYPE x, binary_search_tree& bstTree)
{
if(NULL == bstTree)
{
bstTree= new BSTNODE;
if(NULL != bstTree)
{
bstTree->value = x;
bstTree->left = NULL;
bstTree->right = NULL;
}
}
else
{
if(x < bstTree->value)
{
Insert(x, bstTree->left);
}
else if(x > bstTree->value)
{
Insert(x, bstTree->right);
}
}
return bstTree;
}
BSTNODE* Find(ELEMENTSTYPE x, binary_search_tree bstTree)
{
printf("find/n");
if(NULL == bstTree)
{
return NULL;
}
if(x < bstTree->value)
{
return Find(x, bstTree->left);
}
else if (x > bstTree->value)
{
return Find(x, bstTree->right);
}
else
return bstTree;
}
BSTNODE* find_min(binary_search_tree bstTree)
{
if(NULL == bstTree)
{
return NULL;
}
else if(NULL == bstTree->left)
{
return bstTree;
}
else
{
return find_min(bstTree->left);
}
}
binary_search_tree Delete(ELEMENTSTYPE x, binary_search_tree bstTree)
{
if(NULL == bstTree)
{
return bstTree;
}
else
{
if(x < bstTree->value)
{
Delete(x, bstTree->left);
}
else if(x > bstTree->value)
{
Delete(x, bstTree->right);
}
else
{
if(NULL != bstTree->left && NULL != bstTree->right)
{
BSTNODE* temp = find_min(bstTree->right);
bstTree->value = temp->value;
bstTree->right = Delete(temp->value, bstTree->right);
}
else
{
BSTNODE* temp = bstTree;
if(NULL == bstTree->left)
{
bstTree = bstTree->right;
}
else if(NULL == bstTree->right)
{
bstTree = bstTree->left;
}
delete temp;
}
}
}
return bstTree;
}
}
int main(int argc, char* argv[])
{
using namespace dskit;
binary_search_tree bstTree = NULL;
Insert(1, bstTree);
printf("start find./n");
if(Find(1, bstTree))
{
printf("found./n");
}
if(!Find(2, bstTree))
{
printf("not found./n");
}
return 0;
}