编写算法,输入一组整数,以9999为结束标志,将这些数据建立二叉排序树。输出中序排序序列检验是否为二叉排序树,并且在二叉排序树内查找值。
#include<iostream>
using namespace std;
struct BiNode
{
int key;
int data;
BiNode* lchild, * rchild;
};
class BiSortTree
{
BiNode* root;
void Insert(BiNode*& ptr, int k);
BiNode* Search(BiNode* ptr, int k);
void Free(BiNode* ptr);
//void PreOrder(BiNode* p);
void InOrder(BiNode* p);
//int judgeBST(BiNode* bt);
public:
BiSortTree();
BiSortTree(int a[], int n);
~BiSortTree();
void Insert(int k);
bool Search2(int k);
//void PreOrder();
void InOrder();
//int judgeBST();
};
BiSortTree::BiSortTree()
{
root = NULL;
}
BiSortTree::BiSortTree(int a[], int n)//二叉排序树的建立
{
root = NULL;
for (int i = 0; i < n; i++)
{
Insert(root, a[i]);
}
}
void BiSortTree::InOrder(BiNode* ptr)
{
if (ptr == NULL)
return;
//PreOrder(ptr->lchild);
InOrder(ptr->lchild);
cout << ptr->key << " ";
//PreOrder(ptr->rchild);
InOrder(ptr->rchild);
}
void BiSortTree::InOrder()
{
InOrder(root);
}
BiNode* BiSortTree::Search(BiNode* ptr, int k)//二叉排序树的查找
{
while (ptr)
{
if (k == ptr->key)
{
return ptr;
}
else if (k < ptr->key)
ptr = ptr->lchild;
else
ptr = ptr->rchild;
}
return NULL;
}
bool BiSortTree::Search2(int k)
{
return Search(root, k) != NULL;
}
void BiSortTree::Insert(BiNode*& ptr, int k)//二叉排序树的插入
{
if (ptr == NULL)
{
ptr = new BiNode;
ptr->key = k;
ptr->lchild = ptr->rchild = NULL;
}
else
{
if (k < ptr->key)
Insert(ptr->lchild, k);
else
if (k > ptr->key)
Insert(ptr->rchild, k);
}
}
void BiSortTree::Insert(int k)
{
Insert(root, k);
}
void BiSortTree::Free(BiNode* ptr)//二叉排序树的析构
{
if (ptr == NULL)
return;
Free(ptr->lchild);
Free(ptr->rchild);
delete ptr;
}
BiSortTree::~BiSortTree()
{
Free(root);
}
int main()
{
int i=0;
int a[100];
cout << endl << "请输入序列值,以9999为结束标志: ";
while (1)
{
cin >> a[i];
if (a[i] == 9999)
break;
else
i++;
}
int n;
cout << "请输入这个二叉排序树序列的个数: ";
cin >> n;
cout << endl;
BiSortTree t(a, n);
cout << "请输出中序遍历序列: ";
t.InOrder();
cout << endl;
int item;
cout << endl << "二叉排序树的查找,请输入要查找的值item: ";
cin >> item;
if (t.Search2(item))
cout << endl << "是否找到: " << "找到啦";
else
cout << endl << "是否找到: " << "没找到";
return 0;
}