码迷,mamicode.com
首页 > 其他好文 > 详细

二叉搜索树

时间:2016-04-18 18:34:55      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

#include using namespace std; template struct BSTNode { K _key; V _value; BSTNode *_left; BSTNode *_right; BSTNode(const K&key,const V&value) :_key(key), _value(value), _left(NULL), _right(NULL) {} }; template class BSTree { typedef BSTNode Node; protected: Node* _root; public: BSTree() :_root(NULL) {} ~BSTree() {} bool Insert(const K&key, const V&value) { if (_root == NULL) { _root = new Node(key, value); return true; } Node *parent = NULL; Node *cur = _root; while (cur) { if (cur->_key < key) { parent = cur; cur = cur->_right; } else if (cur->_key > key) { parent = cur; cur = cur->_left; } else { return false; } if (parent->_key < key) { parent->_right = new Node(key, value); } else { parent->_left = new Node(key, value); } return true; } } bool Insert_R(const K&key, const V&value) { return _Insert_R(_root, key, value); } bool _Insert_R(Node*&root,const K&key,const V&value) { if (root == NULL) { root = new Node(key, value); return true; } if (root->_key < key) { return _Insert_R(root->_right, key, value); } if (root->_key >key) { return _Insert_R(root->_left, key, value); } else { return false; } } Node* Find(const K&key) { Node*cur = _root; while (cur) { if (cur->_key > key) { cur = cur->_left; } else if (cur->_key < key) { cur = cur->_right; } else { return cur; } } return NULL; } Node* Find_R(const K&key) { return _Find_R(_root, key); } Node* _Find_R(Node*root, const K&key) { if (root == NULL) { return NULL; } if (root->_key < key) { return _Find_R(root->_right, key); } else if (root->_key>key) { return _Find_R(root->_left, key); } else { return root; } } bool Remove_R(const K&key) { return _Remove_R(_root, key); } bool _Remove_R(Node*& root,const K&key) { if (root == NULL) { return false; } else if (root->_key < key) { return _Remove_R(root->_right, key); } else if (root->_key > key) { return _Remove_R(root->_left, key); } else { Node* del = root; if (root->_left == NULL) { root = root->_right; } else if (root->_right == NULL) { root = root->_left; } else { Node* firstInorder = root->_right; while (firstInorder->_left) { firstInorder = firstInorder->_left; } swap(del->_key, firstInorder->_key); swap(del->_value, firstInorder->_value); return _Remove_R(root->_right, key); } delete del; } } public: void Inorder() { return _Inorder(_root); cout << endl; } void _Inorder(Node* root) { if (root == NULL) return; _Inorder(root->_left); cout << root->_key << " "; _Inorder(root->_right); } }; void Test() { int a[] = { 5, 3, 4, 1, 7, 8, 2, 6, 0, 9 }; BSTree t; for (size_t i = 0; i < sizeof(a) / sizeof(int);++i) { t.Insert_R(a[i], a[i]); } t.Inorder(); //cout<二叉搜索树

标签:

原文地址:http://www.cnblogs.com/yuanshuang/p/5405207.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!