二叉查找树实现

 

 

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值