DS二叉排序树之查找
题目描述
给出一个数据序列,建立二叉排序树,并实现查找功能
对二叉排序树进行中序遍历,可以得到有序的数据序列
输入
第一行输入t,表示有t个数据序列
第二行输入n,表示首个序列包含n个数据
第三行输入n个数据,都是自然数且互不相同,数据之间用空格隔开
第四行输入m,表示要查找m个数据
从第五行起,输入m行,每行一个要查找的数据,都是自然数
以此类推输入下一个示例
输出
第一行输出有序的数据序列,对二叉排序树进行中序遍历可以得到
从第二行起,输出查找结果,如果查找成功输出查找次数,如果查找失败输出-1
以此类推输出下一个示例的结果
样例输入
1
6
22 33 55 66 11 44
7
11
22
33
44
55
66
77
样例输出
11 22 33 44 55 66
2
1
2
4
3
4
-1
#include <iostream>
using namespace std;
class BiNode{
int data;
BiNode *lChild;
BiNode *rChild;
public:
BiNode():lChild(NULL),rChild(NULL){}
BiNode(int e):data(e),lChild(NULL),rChild(NULL){}
friend class BiTree;
};
class BiTree{
BiNode *root;
int count;
void InsertNode(int data,BiNode *&r);
void MidOrder(BiNode *t);
bool Search(int key,BiNode *t);
public:
BiTree(int data){root = new BiNode(data);}
void Insert(int key);
void MidOrder();
void Search(int key);
};
void BiTree::InsertNode(int data,BiNode *&r) {
if(data>r->data && r->rChild)
InsertNode(data,r->rChild);
else if(data < r->data && r->lChild)
InsertNode(data,r->lChild);
else if(data> r->data && !r->rChild)
{
BiNode *s = new BiNode(data);
r->rChild = s;
}
else if(data<r->data && !r->lChild)
{
BiNode *s = new BiNode(data);
r->lChild = s;
}
}
void BiTree::Insert(int key) {
InsertNode(key,root);
}
void BiTree::MidOrder(BiNode *t) {
if(t)
{
MidOrder(t->lChild);
cout<<t->data<<' ';
MidOrder(t->rChild);
}
}
void BiTree::MidOrder() {
MidOrder(root);
cout<<endl;
}
bool BiTree::Search(int key, BiNode *t) {
if(key > t->data && t->rChild)
{
count++;
return Search(key,t->rChild);
}
else if(key <t->data && t->lChild)
{
count++;
return Search(key,t->lChild);
}
else if(key == t->data)
{
count++;
return true;
}
count++;
return false;
}
void BiTree::Search(int key) {
count = 0;
if(Search(key,root))
cout<<count<<endl;
else
cout<<-1<<endl;
}
int main()
{
int t;
cin>>t;
while (t--)
{
int n;
cin>>n;
int data;
cin>>data;
BiTree myTree(data);
for(int i=1;i<n;i++)
{
cin>>data;
myTree.Insert(data);
}
myTree.MidOrder();
int m;
cin>>m;
while (m--)
{
int key;
cin>>key;
myTree.Search(key);
}
}
}