BST树:二叉排序树,二叉排序树
根节点比左边大,比右边小
每一个节点都有关键码,都不一样
左右子树也是二叉搜索树
#include<stdio.h>
#include<queue>
#include<iostream>
using namespace std;
typedef int KeyType;
typedef struct BstNode
{
KeyType key;
BstNode* parent;
BstNode* leftchild;
BstNode* rightchild;
}BstNode,*BSTree;
BstNode* Buynode()
{
BstNode* s = (BstNode*)malloc(sizeof(BstNode));
if (s == NULL)exit(1);
memset(s, 0, sizeof(BstNode));
return s;
}
BstNode* MakeRoot(KeyType kx)
{
BstNode* s = Buynode();
s->key = kx;
return s;
}
bool Insert(BstNode*& ptr, KeyType kx)//插入
{
if (ptr == NULL)
{
ptr = MakeRoot(kx);
return true;
}
BstNode* pa = NULL;
BstNode* p = ptr;
while (p != NULL && p->key != kx)
{
pa = p;
p = kx < p->key ? p->leftchild : p->rightchild;
}
if (p != NULL && p->key == kx)return false;
p = Buynode();
p->key = kx;
p->parent = pa;
if (kx > pa->key)
{
pa->rightchild = p;
}
else
{
pa->leftchild = p;
}
return true;
}
void InOrder(BstNode* ptr)//中序遍历
{
if (ptr != NULL)
{
InOrder(ptr->leftchild);
cout << ptr->key<<" ";
InOrder(ptr->rightchild);
}
}
BstNode* First(BstNode* ptr)//找第一个
{
while (ptr != NULL && ptr->leftchild != NULL)
{
ptr = ptr->leftchild;
}
return ptr;
}
BstNode* Next(BstNode* ptr)//找下一个
{
if (ptr == NULL)return NULL;
if (ptr->rightchild != NULL)
{
return First(ptr->rightchild);
}
else
{
BstNode* pa = ptr->parent;
while (pa != NULL && pa->leftchild!=ptr)
{
ptr = pa;
pa = ptr->parent;
}
return pa;
}
}
BstNode* Last(BstNode* ptr)//找最后一个
{
while (ptr != NULL && ptr->rightchild != NULL)
{
ptr = ptr->rightchild;
}
return ptr;
}
BstNode* Prev(BstNode* ptr)//找前一个
{
if (ptr == NULL)return NULL;
if (ptr->leftchild != NULL)
{
return Last(ptr->leftchild);
}
else
{
BstNode* pa = ptr->parent;
while (pa != NULL && pa->rightchild != ptr)
{
ptr = pa;
pa = pa->parent;
}
return pa;
}
}
void RevNiceInOrder(BstNode* ptr)//从后往前遍历
{
for (BstNode* p = Last(ptr);p != NULL;p = Prev(p))
{
cout << p->key << " ";
}
cout << endl;
}
bool Remove(BstNode*& ptr, KeyType kx)//删除某一个节点
{
if (ptr == NULL)return false;
BstNode* pa = NULL;
BstNode* p = ptr;
while (p != NULL && p->key != kx)
{
p = kx < p->key ? p->leftchild : p->rightchild;
}
if (p == NULL)return false;
if (p->leftchild != NULL && p->rightchild != NULL)//如果是双节点,把他和右边最左边的节点只删掉,这样就变成删除单节点了
{
BstNode* q = First(p->leftchild);
p->key = q->key;
p = q;
}
pa = p->parent;
BstNode* child = p->leftchild != NULL ? p->leftchild : p->rightchild;
if (child != NULL)child->parent = pa;//有单个节点
if (pa == NULL)//删除根结点
{
ptr = child;
}
else
{
if (pa->leftchild == p)
{
pa->leftchild = child;
}
else
{
pa->rightchild = child;
}
}
free(p);
return true;
}
int main()
{
BSTree root = NULL;
int ar[] = { 53,17,78,9,45,65,87,23,81,94,88,100 };
int n = sizeof(ar) / sizeof(ar[0]);
for (int i = 0;i < n;++i)
{
cout << Insert(root, ar[i]) << endl;
}
InOrder(root);
cout << endl;
RevNiceInOrder(root);
return 0;
}