一、二叉排序树
1、定义:对于根节点,若左子树不空,则左子树上所有节点值小于根节点,若右子树不空,则右子树所有节点值大于等于根节点,左右子树也是二叉排序树。
2、构造:按关键字读入次序构造。第一个关键字作为根节点,然后每读入一个关键字,就与根节点比较,若较小,则当左子树为空时,把它作为根的左孩子,若左子树非空,则把它插入根的左子树上;若较大,则当右子树为空时,把它作为根的右孩子,若右子树非空,则把它插入根的右子树上。
3、二叉排序树建立、插入、删除、查找、前序遍历、中序遍历:
#include <iostream>
#include <vector>
using namespace std;
struct BiNode
{//二叉排序树节点的数据类型
int key;
BiNode *lchild,*rchild;
};
class BiSortTree{
public:
BiSortTree(int a[],int n);//构造函数
BiNode *Getroot();//获取指向根节点的指针
void pre_order(BiNode *root);//前序遍历二叉树
void mid_order(BiNode *root);//中序遍历二叉树
BiNode *CreatBiSortTree(int a[],int n);//建立二叉排序树
BiSortTree(){};//构造函数
BiNode *InsertBST(BiNode *root,BiNode *s);//非递归插入节点s
BiNode *InsertBST1(BiNode *root,BiNode *s);//递归插入节点s
void DeleteBST(BiNode *p,BiNode *f);//删除节点p,f是p的双亲节点
void NextRep(BiNode *p);//删除节点p,查找中序序列中p的后继s代替p
BiNode *SearchBST(BiNode *root,int k);//查找,非递归
BiNode *SearchBST1(BiNode *root,int k);//查找,递归
private:
BiNode *root;
};
BiSortTree::BiSortTree(int a[],int n)//构造函数
{
BiNode *root=NULL;
for(int i=0;i<n;i++)
{
BiNode *s=new BiNode;
s->key=a[i];
s->lchild=NULL;
s->rchild=NULL;
root=InsertBST1(root,s);
}
}
//前序遍历二叉树
void BiSortTree::pre_order(BiNode *root)
{
if(root!=NULL)
{
cout<<root->key<<" ";
pre_order(root->lchild);
pre_order(root->rchild);
}
}
void BiSortTree::mid_order(BiNode *root)//中序遍历二叉树
{
if(root)
{
mid_order(root->lchild);
cout<<root->key<<" ";
mid_order(root->rchild);
}
}
//二叉排序树上插入一个关键字(非递归)
BiNode *BiSortTree::InsertBST(BiNode *root,BiNode *s)
{//在根为root的树上插入节点s,若树空则插入s为根节点,否则,根据值的大小选择插入左子树还是右子树
BiNode *p,*q;
if(!root) return s;
else
{
q=NULL;p=root;
while(p)
{
q=p;//q为p的根
if(s->key<p->key) p=p->lchild;
else p=p->rchild;
}//s插入节点q的左孩子或右孩子
if(s->key