編程演算法 - 二叉搜尋樹(binary search tree) 代碼(C)

來源:互聯網
上載者:User

標籤:mystra   編程演算法   二叉搜尋樹   代碼   c   

二叉搜尋樹(binary search tree) 代碼(C)


本文地址: http://blog.csdn.net/caroline_wendy


二叉搜尋樹(binary search tree)可以高效的進行插入, 查詢, 刪除某個元素, 時間複雜度O(logn).

簡單的實現方法如下.

代碼:

/* * main.cpp * *  Created on: 2014.7.20 *      Author: spike *//*eclipse cdt, gcc 4.8.1*/#include <stdio.h>#include <queue>#include <vector>#include <functional>using namespace std;struct node {int val;node *lch, *rch;};class BinarySearchTree {public:node *insert(node *p, int x) {if (p==NULL) {node* q = new node;q->val = x;q->lch = q->rch = NULL;return q;} else {if (x<p->val) p->lch = insert(p->lch, x);else p->rch = insert(p->rch, x);return p;}}bool find(node *p, int x) {if (p==NULL) return false;else if (x==p->val) return true;else if (x<p->val) return find(p->lch, x);else return find(p->rch, x);}node *remove(node *p, int x) {if (p==NULL) return NULL;else if (x<p->val) p->lch = remove(p->lch, x);else if (x>p->val) p->rch = remove(p->rch, x);else if (p->lch == NULL) {node* q=p->rch;delete p;return q;} else if (p->lch->rch == NULL) {node* q = p->lch;q->rch = p->rch;delete p;return q;} else {node* q;for (q = p->lch; q->rch->rch!=NULL; q=q->rch);node* r = q->rch;q->rch = r->lch;r->lch = p->lch;r->rch = p->rch;delete p;return r;}return p;}};int main(void){BinarySearchTree iBST;node* root = NULL;root = iBST.insert(root, 7);root = iBST.insert(root, 2);root = iBST.insert(root, 15);root = iBST.insert(root, 1);root = iBST.insert(root, 5);root = iBST.insert(root, 10);root = iBST.insert(root, 17);root = iBST.insert(root, 4);root = iBST.insert(root, 6);root = iBST.insert(root, 8);root = iBST.insert(root, 11);root = iBST.insert(root, 16);root = iBST.insert(root, 19);bool isOK = iBST.find(root, 15);printf("result = %s\n", isOK?"Yes":"No");iBST.remove(root,15);isOK = iBST.find(root, 15);printf("result = %s\n", isOK?"Yes":"No");isOK = iBST.find(root, 10);printf("result = %s\n", isOK?"Yes":"No");return 0;}

輸出;

result = Yesresult = Noresult = Yes







編程演算法 - 二叉搜尋樹(binary search tree) 代碼(C)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.