二叉搜索树

#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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值