题目描述
给出一个数据序列,建立二叉排序树,并实现查找功能
对二叉排序树进行中序遍历,可以得到有序的数据序列
输入
第一行输入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
查找实现:
和插入一样的比较方法
temp初始化为根结点
每次判断要查找的值和结点temp的值的大小
如果temp为NULL,结束,返回-1表示没找到
如果要查找的值等于temp,直接结束,返回比较次数
如果要查找的值比temp大,temp=temp->Rightchild,继续查找
如果要查找的值比temp小,temp=temp->Leftchild,继续查找
代码:
#include <iostream>
#include <queue>
#include <string>
using namespace std;
class BSTNode{
public:
int data;
BSTNode *LeftChild;
BSTNode *RightChild;
public:
BSTNode():LeftChild(NULL),RightChild(NULL){};
~BSTNode(){};
};
class BST{
public:
BSTNode *Root;
public:
BST(){};
~BST(){};
void Create();
void Inorder(BSTNode *t);
void Insert();
int Search();
};
void BST::Create()
{
int n,temp_num;
cin>>n;
Root = new BSTNode();
cin>>Root->data;
BSTNode *temp;
for(int i=0;i<n-1;i++)
{
cin>>temp_num;
temp=Root;
while(1)
{
if(temp->data > temp_num)
{
if(temp->LeftChild !=NULL)
temp=temp->LeftChild;
else
{
BSTNode *lc = new BSTNode();
temp->LeftChild = lc;
lc->data = temp_num;
break;
}
}
else
{
if(temp->RightChild !=NULL)
temp=temp->RightChild;
else
{
BSTNode *lc = new BSTNode();
temp->RightChild = lc;
lc->data = temp_num;
break;
}
}
}
}
}
void BST::Inorder(BSTNode *t)
{
if(t->LeftChild != NULL)
Inorder(t->LeftChild);
cout<<t->data<<' ';
if(t->RightChild != NULL)
Inorder(t->RightChild);
}
void BST::Insert()
{
int temp_num;
cin>>temp_num;
BSTNode *temp;
temp=Root;
while(1)
{
if(temp->data > temp_num)
{
if(temp->LeftChild !=NULL)
temp=temp->LeftChild;
else
{
BSTNode *lc = new BSTNode();
temp->LeftChild = lc;
lc->data = temp_num;
break;
}
}
else
{
if(temp->RightChild !=NULL)
temp=temp->RightChild;
else
{
BSTNode *lc = new BSTNode();
temp->RightChild = lc;
lc->data = temp_num;
break;
}
}
}
}
int BST::Search()
{
int num;
cin>>num;
BSTNode *temp;
temp = Root;
int time=0;
while(1)
{
if(temp == NULL)
return -1;
time++;
if(temp->data == num)
return time;
else if(temp->data > num)
temp=temp->LeftChild;
else
temp=temp->RightChild;
}
}
int main()
{
int t,insert_num;
cin>>t;
while(t--)
{
BST t;
t.Create();
t.Inorder(t.Root);
cout<<endl;
cin>>insert_num;
while(insert_num--)
{
cout<<t.Search()<<endl;
}
}
}