這篇文章主要介紹了C++如何實現(xiàn)二叉搜索樹,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
具體代碼如下所示:
class BST { public: struct Node { int key;//節(jié)點的key int value;//節(jié)點的value Node* left; Node *right; int N;//節(jié)點的葉子節(jié)點數(shù)目 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); }
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“C++如何實現(xiàn)二叉搜索樹”這篇文章對大家有幫助,同時也希望大家多多支持創(chuàng)新互聯(lián)建站,關(guān)注創(chuàng)新互聯(lián)網(wǎng)站建設(shè)公司行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)建站chinadenli.net,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機、免備案服務(wù)器”等云主機租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。
本文標(biāo)題:C++如何實現(xiàn)二叉搜索樹-創(chuàng)新互聯(lián)
URL網(wǎng)址:http://chinadenli.net/article18/cdjdgp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站策劃、網(wǎng)站建設(shè)、自適應(yīng)網(wǎng)站、虛擬主機、微信公眾號、ChatGPT
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容