建立二叉排序樹
阿新 • • 發佈:2021-01-12
編寫演算法,輸入一組整數,以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;
}