二叉搜索树(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 = Yes
result = No
result = Yes

版权声明:本文博主原创文章,博客,未经同意不得转载。

最新文章

  1. H5+JS+CSS3 综合应用
  2. 【译】Visual Studio 15 预览版更新说明
  3. linux服务器下添加字体
  4. CLR VIA C#事件
  5. HTTP权威指南阅读笔记一:HTTP概述
  6. percona 5.6升级到5.7相关error及解决方法
  7. mac 下修改Hosts文件
  8. 关于C语言读取多行数据的问题
  9. 自动化中的PageObject思想
  10. Linux下如何发布Qt程序
  11. 背包问题--nyoj题目106
  12. ubuntu新内核不能用启动回滚到旧内核的方法
  13. vue.js中ajax请求
  14. Exclusive-OR(带权并查集)
  15. 学习爬虫的day03 (通过代理去爬去数据)
  16. 速微共享链的使用步骤和源码分析(UI设计参考)
  17. 业余草分享 Spring Boot 2.0 正式发布的新特性
  18. markdown文本转换word,pdf
  19. 20165223《JAVA程序设计》第一周学习总结
  20. hive视图

热门文章

  1. C语言深度剖析-----数组参数和指针参数分析
  2. ZOJ 2679 Old Bill ||ZOJ 2952 Find All M^N Please 两题水题
  3. HDU 1251统计难题 字典树
  4. 前端实时消息提示的效果-websocket长轮询
  5. wireshark分析包中关于三次握手和四次终止标识
  6. AForge,Emgu.CV抓拍图像大小
  7. Java中关键字throw和throws的区别
  8. ArcSDE:C#打开SDE数据库的几种方式总结
  9. irms模拟数据生成及数据分析 分类: H_HISTORY 2015-03-06 14:17 212人阅读 评论(0) 收藏
  10. thinkphp5 tp5 获取模块名控制器名方法名