二叉查找树的实现(BST)
来源:互联网 发布:张伟华 知乎 编辑:程序博客网 时间:2024/05/16 01:47
用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;
}
- 二叉查找树的实现(BST)
- BST 二叉查找树的实现
- 二叉查找树的实现(BST)
- 二叉查找树(BST)的实现
- BST二叉查找树实现
- BST二叉查找树的实现与操作
- 二叉查找树(二叉排序树)的详细实现(BST)
- 【学习笔记】二叉查找树(BST)的实现
- Java实现BST(二叉查找树)
- 二叉查找树BST----java实现
- 二叉查找树BST----java实现
- Java实现二叉查找树(BST)
- BST二叉查找树
- BST二叉查找树
- 二叉查找树 BST
- BST二叉查找树
- 二叉查找树BST
- 二叉查找树BST
- 3、路漫漫其修远兮,吾将上下而求索...
- QT的Graphics View柜架(1/3)
- 软件版本变更的一点感触
- 各种数据库连接方式(简单总结)
- Calendar.set用法的深入探讨
- 二叉查找树的实现(BST)
- 日本のたこ
- http://www.joelonsoftware.com/
- 有没有办法创建一个快捷方式指向两个不同的路径?
- DBminitor|P6Spy---- record sql
- exec函数族
- 两个小程序:atoi & 统计整数的二进制表示里有几个1
- 坚持创造奇迹
- 图标网站收集(ICO、PNG)