二叉搜索树实现(继承于二叉树)
1
#include "BinTree.h"
2
3
template<class K,class E>
4
class BinSearchTree:public BinTree<E>
5

{
6
public:
7
bool Search(const K &k,E &e);//以关键字K进行搜索,结果返回到e中
8
BinSearchTree<K,E>& Insert(const E &e);//将元素e插入到树中
9
BinSearchTree<K,E>& Delete(const K &k,E &e);//通过指定关键字k进行节点的删除
10
11
};
12
13
//----------------------------------------------------------
14
template<class K,class E>
15
bool BinSearchTree<K,E>::Search(const K &k,E &e)
16

{
17
18
BinTreeNode<E> *p=root;
19
while(p)
20

{
21
if(k<p->data)
22
p=p->LeftChild;
23
else if(k>p->data)
24
p=p->RightChild;
25
else//找到元素
26

{
27
e=p->data;
28
return true;
29
}
30
}
31
return false;
32
}
33
//----------------------------------------------------------
34
template<class K,class E>
35
BinSearchTree<K,E>& BinSearchTree<K,E>::Insert(const E &e)
36

{
37
38
BinTreeNode<E> *p=root,*pp=NULL;
39
while(p)
40

{
41
pp=p;
42
if(e<=p->data)
43
p=p->LeftChild;
44
else
45
p=p->RightChild;
46
}
47
48
BinTreeNode<E> *NewNode=new BinTreeNode<E>(e);
49
if(root)
50

{
51
if(e<=pp->data)
52
pp->LeftChild=NewNode;
53
else
54
pp->RightChild=NewNode;
55
}
56
else
57
root=NewNode;
58
return *this;
59
}
60
61
//----------------------------------------------------------
62
template<class K,class E>
63
BinSearchTree<K,E>& BinSearchTree<K,E>::Delete(const K &k,E &e)
64

{
65
BinTreeNode<E> *p=root,*pp=NULL;
66
67
while(p&&p->data!=k)
68

{pp=p;
69
if(k<p->data) p=p->LeftChild;
70
else p=p->RightChild;
71
}
72
73
if(!p)
{throw exception("没有找到指定元素");}
74
e=p->data;
75
if(p->LeftChild&&p->RightChild)//p的左右孩子均不为空
76

{
77
BinTreeNode<E> *s=p->LeftChild,*ps=p;
78
while(s->RightChild)
79

{
80
ps=s;
81
s=s->RightChild;
82
}
83
84
p->data=s->data;
85
p=s;
86
pp=ps;
87
}//if
88
BinTreeNode<E> *c;
89
if(p->LeftChild) c=p->LeftChild;
90
else c=p->RightChild;
91
92
if(p==root) root=c;
93
else
94

{
95
96
if(p==pp->LeftChild) pp->LeftChild=c;
97
else pp->RightChild=c;
98
}
99
delete p;
100
101
return *this;
102
}
posted on 2008-09-18 17:17
杨彬彬 阅读(1230)
评论(0) 编辑 收藏 引用 所属分类:
数据结构