C++ 实现二叉搜索树(BST)
来源:互联网 发布:法丽达官网 只有淘宝店 编辑:程序博客网 时间:2024/06/06 07:10
class BST{public: struct Node { int key;//节点的key int value;//节点的value Node* left; Node *right; int N;//节点的叶子节点数目 Node(int _key, int _value, int _N) { key = _key; value = _value; N = _N; } }; BST(); ~BST(); void put(int key, int value); int get(int key); int deleteKey(int key);private: Node* _deleteKey(int key, Node *x); Node* _deleteMin(Node *x); int size(Node *x); int _get(int key, Node* x); Node * _put(int key, int value,Node *x); Node * min(Node *x); Node* root;};inline int BST::size(Node * x){ if (x == nullptr)return 0; return x->N;}int BST::_get(int key, Node * x){ if (x == nullptr)return 0; if (x->key < key)_get(key, x->right); else if (x->key > key)_get(key, x->left); else { return x->value; } return 0;}BST::Node* BST::_put(int key, int value, Node * x){ if (x == nullptr) { Node *tmp = new Node(key, value, 1); return tmp; } if (x->key > key) { x->left=_put(key, value, x->left); } else if (x->key < key) { x->right=_put(key, value, x->right); } else x->key = key; x->N = size(x->left) + size(x->right) + 1; return x;}BST::Node* BST::min(Node * x){ if (x->left == nullptr)return x; return min(x->left);}BST::BST(){}BST::~BST(){}void BST::put(int key, int value){ root=_put(key, value, root);}int BST::get(int key){ return _get(key, root);}BST::Node* BST::_deleteKey(int key, Node * x){ if (x->key > key)x->left = _deleteKey(key, x->left); else if (x->key < key)x->right = _deleteKey(key, x->right); else { if (x->left == nullptr)return x->right; else if (x->right == nullptr)return x->left; else { Node *tmp = x; x = min(tmp->right); x->left = tmp->left; x->right = _deleteMin(tmp->right); } } x->N = size(x->left) + size(x->right) + 1; return x;}BST::Node* BST::_deleteMin(Node * x){ if (x->left == nullptr)return x->right; x->left = _deleteMin(x->left); x->N = size(x->left) + size(x->right) + 1; return x;}int BST::deleteKey(int key){ return _get(key, root);}
0 0
- 【C++】实现的二叉搜索树BST
- 二叉搜索树(BST) ----- C语言
- BST二叉搜索树的实现
- 二叉搜索树【BST】c++实现
- 搜索二叉树(BST)的实现
- 二叉搜索树BST的C++实现
- C++ 实现二叉搜索树(BST)
- BST 二叉搜索树
- 二叉搜索树BST
- 二叉搜索树BST
- 二叉搜索树(BST)
- BST-搜索二叉树
- BST二叉搜索树
- Linux c 二叉搜索树(节点创建、插入BST)
- BST(二叉树搜索树)
- 二叉搜索树(BST树)
- *BST(二叉搜索树)
- 二叉搜索树(BST)
- VerticalSeekBar 竖直滑动条
- windowns安装git客户端
- 什么是用户故事地图?
- 0.《Mysql必知必会》数据库的基本概念
- Singleton模式
- C++ 实现二叉搜索树(BST)
- 使用 Cocoapods 集成框架 Operation not permitted
- Linux数据库:MySQL新建用户,授权,删除用户,修改密码
- 汉诺塔问题
- JS的MVVM库和原生DOM的区别
- jQuery 数据操作函数
- python下安装dlib(boost.python的编译)
- 给map集合字母排序
- Ajax 同步提示 beforeSend的另类解决方法