二叉排序树(BinarySortTree)的实现
2013-03-16 20:57
295 查看
/* Title : Binary Sort Tree Author: nyist_xiaod Date : 2013.3.16 */ #include <stdio.h> #include <string.h> #include <algorithm> using namespace std; #define BSTdef #define Pnn pair<Node*,Node*> #ifdef BSTdef #define Pre(root,parent) (root==Root ? Root : (value < parent->value ? parent->lson : parent->rson)) #endif template<typename T> struct BST { struct Node { T value; Node *lson, *rson; Node(const T& val):value(val),lson(NULL),rson(NULL){} }; Node* Root; /**********************************************/ BST():Root(NULL){} bool empty() { return Root == NULL; } void clear(Node* root) { if(root == NULL) return ; clear(root->lson); clear(root->rson); delete root; root = NULL; } Node* least(Node* root) { return root->lson ? least(root->lson) : root; } Node* most(Node* root) { return root->rson ? most(root->rson) : root; } Pnn search(const T& value) { Node *root = Root , *parent = NULL; while(root) { if(value == root->value) return make_pair(root,parent); parent = root; root = value < parent->value ? parent->lson : parent->rson; } return make_pair(root,parent); } bool insert(const T& value) { Pnn p = search(value); Node *root = p.first , *parent = p.second; if(root != NULL) return false; Pre(root,parent) = new Node(value); return true; } void erase(const T& value) { Pnn p = search(value); Node *root = p.first , *parent = p.second; if(root->lson == NULL) Pre(root,parent) = root->rson; else if(root->rson == NULL) Pre(root,parent) = root->lson; else { Node *lmost = root->lson, *lparent = root; while(lmost->rson) { lparent = lmost; lmost = lmost->rson; } (lmost->value < lparent->value ? lparent->lson : lparent->rson) = lmost->lson; lmost->lson = root->lson , lmost->rson = root->rson; Pre(root,parent) = lmost; } delete root; } };
相关文章推荐
- 二叉排序树(Binary Sort Tree)查找、插入、删除 Java实现
- 数据结构之---C语言实现二叉排序树(BinarySortTree)
- 查询二叉树——Binary Sort Tree 设计与实现
- 二叉排序树binary_sort_tree
- 二叉排序树binary_sort_tree
- [数据结构]程杰—— 二叉排序树_BinarySortTree
- 【LeetCode-面试算法经典-Java实现】【109-Convert Sorted List to Binary Search Tree(排序链表转换成二叉排序树)】
- BST(Binary Search Tree,二叉查找树,二叉排序树)c的实现(部分函数不知如何调用)
- 二叉排序树BinarySortTree(二叉搜索树Binary Search Tree)
- 二叉排序树(Binary Sort Tree)
- 平衡二叉树——Balance Binary Sort Tree 设计与实现
- 【LeetCode-面试算法经典-Java实现】【109-Convert Sorted List to Binary Search Tree(排序链表转换成二叉排序树)】
- 二叉排序树(Binary Sort Tree)
- 【数据结构】二叉排序树_BinarySortTree
- 算法学习记录-查找——二叉排序树(Binary Sort Tree)
- 二叉排序树(Binary Sort Tree)的查找递归算法
- 二叉排序树(Binary Sort Tree)
- 二叉排序树(Binary Sort Tree)
- 大话数据结构 code 第八章 02二叉排序树_BinarySortTree
- 二叉排序树/二叉查找树 (binary sort tree/ binary search tree)的C语言实现