(十三)、C++二叉排序树(BST c风格)
#include <iostream>
using namespace std;
using Tree = struct Tree
{
int data;
Tree* lchild, * rchild;
Tree() :data(), lchild(nullptr), rchild(nullptr) {}
Tree(int da) :data(da), lchild(nullptr), rchild(nullptr) {}
};
Tree* BST_Seach(Tree* T, int key)
{
while (T != nullptr && key != T->data)
{
if (key < T->data)
{
T = T->lchild;
}
else
{
T = T->rchild;
}
}
return T;
}
Tree* BSTSeah(Tree* T, int key)
{
if (T == nullptr)
{
return nullptr;
}
if (key == T->data)
{
return T;
}
else if (key < T->data)
{
return BSTSeah(T->lchild, key);
}
else
{
return BSTSeah(T->rchild, key);
}
}
int BST_Insert(Tree*& T, int k)
{
if (T == nullptr)
{
T = new Tree(k);
return 1;
}
else if (k == T->data)
{
return 0;
}
else if (k < T->data)
{
return BST_Insert(T->lchild, k);
}
else
{
return BST_Insert(T->rchild, k);
}
}
int BST_InsertLive(Tree*& T, int k)
{
while (T != nullptr && T->data != k)
{
if (T == nullptr)
{
T = new Tree(k);
return 1;
}
if (k == T->data)
{
return 0;
}
else if (k < T->data)
{
T = T->lchild;
}
else
{
T = T->rchild;
}
}
return 0;
}
int successor(Tree* p)
{
p = p->rchild;
while (p->lchild != nullptr)
{
p = p->lchild;
}
return p->data;
}
int predecessor(Tree* p)
{
p = p->lchild;
while (p->rchild != nullptr)
{
p = p->rchild;
}
return p->data;
}
Tree* BST_Delete(Tree*& T, int key)
{
if (T == nullptr)
{
return nullptr;
}
else
{
if (key < T->data)
{
T->lchild = BST_Delete(T->lchild, key);
}
else if (key > T->data)
{
T->rchild = BST_Delete(T->rchild, key);
}
else
{
if (T->lchild == nullptr && T->rchild == nullptr)
{
T = nullptr;
}
else if (T->rchild != nullptr)
{
T->data = successor(T);
T->rchild = BST_Delete(T->rchild, T->data);
}
else
{
T->data = predecessor(T);
T->lchild = BST_Delete(T->lchild, T->data);
}
}
}
return T;
}
void Create_BST(Tree*& T, int str[], int n)
{
T = nullptr;
int i = 0;
while (i < n)
{
BST_Insert(T, str[i]);
i++;
}
}
void Printf(Tree* T)
{
if (T != nullptr)
{
Printf(T->lchild);
cout << T->data << " ";
Printf(T->rchild);
}
}
int main()
{
int str[5] = { 50,66,60,26,21 };
Tree* T = new Tree;
Create_BST(T, str, 5);
Printf(T);
return 0;
}