您的位置:首页 > 其它

二叉查找树实现

2008-02-27 23:30 281 查看
#ifndef BSTREE_H
#define BSTREE_H

#include "binaryTree.h"

template <class K>
class BSTree:public BinaryTree<K>
{
public:
BSTree(BinaryTreeNode<K> *root=NULL):BinaryTree<K>(root) { }
bool search(const K k);
BSTree<K>& insert(const K k);
BSTree<K>& deleteNode(const K k);
};

#include "BSTree.cpp"

#endif

//BSTree.cpp

template <class K>
bool BSTree<K>::search(K k)
{
BinaryTreeNode<K> *t = root;
while (t)
{
if(t->key == k)
{
cout<<k<<" exists!"<<endl;
return true;
}
else if (k > t->key)
t = t->right;
else if(k < t->key)
t = t->left;
}
cout<<k<<" not exists!"<<endl;
return false;
}

template <class K>
BSTree<K>& BSTree<K>::insert(const K k)
{
BinaryTreeNode<K> *p = root,*pp;
while(p)
{
pp = p;
if(k > p->key)
p = p->right;
else if(k < p->key)
p = p->left;
else
{
cout<<"the value to be inserted exists!"<<endl;
return *this;
}
}
BinaryTreeNode<K> *temp = new BinaryTreeNode<K>(k);
if (NULL == temp)
{
cout<<"new error!"<<endl;
return *this;
}
if(root)
{
if(k > pp->key)
pp->right = temp;
else
pp->left = temp;
}
else
root = temp;

return *this;
}

template <class K>
BSTree<K>& BSTree<K>::deleteNode(const K k)
{

BinaryTreeNode<K> *p = root, *pp = root;
while (p && p->key != k)
{
pp = p;
if(k > p->key)
p = p->right;
else
p = p->left;
}

if (p == NULL)
{
cout<<"no "<<k<<endl;
return *this;
}

if (p->left && p->right)
{
BinaryTreeNode<K> *s=p->left,*ps = p;
while (s->right)
{
ps = s;
s = s->right;
}

p->key = s->key;
p = s;
pp = ps ;
}

BinaryTreeNode<K> *c;

if (p == pp)
{
root = p->right;
}

if (p->left)
c = p->left;
else
c = p->right;

if (p == pp->left)
{
pp->left = c;
}
else if (p == pp->right)
{
pp->right = c;
}
delete p;
p = NULL;
return *this;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: