算法导论笔记之----二叉搜索树的插入、删除、搜索操作
2012-07-24 08:15
363 查看
#include<iostream> using namespace std; struct tree { int Key; tree *left; tree *right; }; void SetNull(tree *&Root,int x); void Insert(tree *&Root,int x) { if(Root==NULL) { Root=new tree; Root->Key=x; Root->left =Root->right=NULL; return ; } else { if(Root->Key<x) Insert(Root->right ,x); else Insert(Root->left,x); } return ; } //在2叉树中搜索某个元素 bool Find ( tree *&Root,const int& x) { if(Root==NULL) return false; else if(Root->Key==x) return true; else { if(Root->Key<x) Find(Root->right,x); else Find(Root->left,x); } } //寻找某个元素的位置 tree *find(tree *Root,const int &x) { if(Root->Key==x) return Root; else { if(x<Root->Key) find(Root->left,x); else find(Root->right,x); } } //有一个孩子为空 void Delete1(tree *&Root,const int &x) { Root->left ==NULL?Root=Root->right:Root=Root->left; } //都为空 void Delete2(tree *&Root,const int &x) { Root=NULL; } //左右孩子都不为空时 void Delete3(tree *&Root,const int &x) { tree *node=new tree; node=Root->right; while(node->left!=NULL) node=node->left; SetNull(Root->right ,node->Key); Root->Key=node->Key; } //删除某一个节点 void Delete (tree *&Root,const int &x) { if(Root->Key==x) { if(Root->left!=NULL&&Root->right!=NULL) Delete3(Root,x); else if(Root->left==NULL&&Root->right==NULL) Delete2(Root,x); else Delete1(Root,x); } else if(Root->Key<x) Delete(Root->right ,x); else Delete(Root->left,x); } //将某个节点设置为空 void SetNull(tree *&Root,int x) { if(Root->Key==x) Root=NULL; else if(Root->Key<x) SetNull(Root->right ,x); else SetNull(Root->left,x); } int main() { int x; tree *Root; Root=NULL; while(cin>>x,x) Insert(Root,x); cin>>x; Delete(Root,x); return 0; } //20 10 30 5 15 25 35 3 8 12 17 1 4 6 9
在删除操作中处理第三种情况采用算法导论中所描述的,直接将要删除的节点用改节点后继替代,同时将后继清空。例如图中5的后继为6,10的前继为9.。
相关文章推荐
- Java创建二叉搜索树,实现搜索,插入,删除操作
- Java创建二叉搜索树,实现搜索,插入,删除操作
- Java创建二叉搜索树,实现搜索,插入,删除的操作实例
- 【二叉树】二叉搜索树创建、插入、删除、查找等操作
- 学习笔记——C语言实现单链表的基本操作:创建、输出、插入结点、删除结点、逆序链表
- 【二叉树】二叉搜索树创建、插入、删除、查找等操作
- 数据结构与算法分析学习笔记--第四章(搜索二叉树,递归和非递归实现删除、插入)
- 二叉搜索树的相关操作:插入节点,删除节点,排序,查找,最大值,最小值,前序,中序,后序遍历(主要用到递归的方法)
- 数据结构基础5.2:二叉搜索树(BST)的基本操作(插入、查找、删除)
- 二叉搜索树的查找、插入、删除操作
- [C++]数据结构:平衡的二叉搜索树之AVL树的结构特点与基础插入删除操作
- 二叉搜索树(BST)的常用操作:建树、插入、查询、删除、排序打印
- 【难】【BET】无重复值的搜索二叉树的插入和删除操作
- 排序二叉树常规操作(搜索,插入,删除,最大节点,最小节点)
- Skip list -- 跳跃表的插入删除搜索等ADT操作的实现与测试
- 学习笔记:B树建立,搜索和删除操作
- 优先队列、链表数组二叉搜索树的插入删除操作
- 二叉搜索树的根插入、选择、删除、合并、排序等操作的实现
- 算法导论中十二章C++实现二叉查找树建立,插入,删除,遍历操作
- 二叉搜索树的插入和删除结点操作以及iterator的构造