#pragma once
#ifndef _BST_H_
#define _BST_H_
#include <assert.h>
#include <iostream>
using namespace std;
struct Student
{
long ID_number;
char name[12];
char sex;
char address[12];
};
struct BSTNode //二叉树节点类;
{
Student data;
BSTNode *left, *right;
BSTNode() : left(NULL), right(NULL) { }
BSTNode(const Student d, BSTNode *L=NULL, BSTNode *R=NULL) : data(d), left(L), right(R) { }
~BSTNode() { }
void setData(Student d) {data=d;}
Student getData() {return data;}
};
class BST //二叉搜索树的类定义;
{
public:
BST() : root(NULL) { }
~BST() { };
bool Search(const long x) {return Search(x, root)!=NULL;}
Student Min() {return Min(root)->data;}
Student Max() {return Max(root)->data;}
bool Insert(const Student& e1) {return Insert(e1, root);}
bool Remove(const long x) {return Remove(x, root);}
private:
BSTNode *Search(const long x, BSTNode *ptr)
{
if(ptr==NULL) return NULL;
else if(x<ptr->data.ID_number) return Search(x, ptr->left);
else if(x>ptr->data.ID_number) return Search(x, ptr->right);
else return ptr;
}
BSTNode *Min(BSTNode *ptr) const
{
if(ptr==NULL) return NULL;
while(ptr->left!=NULL) ptr=ptr->left;
return ptr;
}
BSTNode *Max(BSTNode *ptr) const
{
if(ptr==NULL) return NULL;
while(ptr->right!=NULL) ptr=ptr->right;
return ptr;
}
bool Insert(const Student& e1, BSTNode *&ptr)
{
if(ptr==NULL)
{
ptr=new BSTNode(e1); assert(ptr!=NULL);
return true;
}
if(e1.ID_number<ptr->data.ID_number) Insert(e1, ptr->left);
if(e1.ID_number>ptr->data.ID_number) Insert(e1, ptr->right);
return false;
}
bool Remove(const long x, BSTNode *&ptr)
{
BSTNode *temp;
if(ptr!=NULL)
{
if(x<ptr->data.ID_number) Remove(x, ptr->left);
else if(x>ptr->data.ID_number) Remove(x, ptr->right);
else if(ptr->left!=NULL&&ptr->right!=NULL)
{
temp=ptr->right;
while(temp->left!=NULL) temp=temp->left;
ptr->data=temp->data;
Remove(ptr->data.ID_number, ptr->right);
}
else
{
temp=ptr;
if(ptr->left==NULL) ptr=ptr->right;
else ptr=ptr->left;
delete temp; return true;
}
}
return false;
}
private:
BSTNode *root;
long RefValue;
};
#endif
二叉搜索树
最新推荐文章于 2024-01-29 23:24:42 发布