生成N个结点的随机二叉查找树
完成这个程序需要三个主要功能实现,生成N个随机结点,生成一颗二叉查找树储存这N个结点,计算程序运行时间。
- 生成N个随机的结点:
我采用的方法是生成一个数组,数组按序存储,然后生成伪随机数交换数组元素即可 - 实现二叉查找树:
因为我不想使用二级指针,所以我在设计的时候每次返回根结点地址,若根结点为空则为其开辟一个结点空间使其数据域储存待插入元素,若非空则每次使用一个结点指针记录结点地址循环定位到合适位置生成一个结点储存待插入元素,然后使新生成的结点为结点指针保存的结点的子结点即可。 - 计算程序运行时间:
先定义两个类型为cpu时钟计时单元数(clock_t)的变量,分别在主函数的开始与结束时记录时间,最后输出两个变量的差值再除以每枚cpu有多少个时钟单元即可得到时间。
#include <time.h>
int main()
{
clock_t start, finish;
//clock_t为CPU时钟计时单元数
start = clock();
//clock()函数返回此时CPU时钟计时单元数
/*
你的代码
*/
finish = clock();
//clock()函数返回此时CPU时钟计时单元数
cout <<endl<<"the time cost is:" << double(finish - start) / CLOCKS_PER_SEC<<endl;
//finish与start的差值即为程序运行花费的CPU时钟单元数量,再除每秒CPU有多少个时钟单元,即为程序耗时
return 0;
}
整体代码;
#include<iostream>
#include<stack>
#include<ctime>
#include<cstdlib>
typedef struct Treenode{
int data=0;
struct Treenode* Left=nullptr;
struct Treenode* Right=nullptr;
}Treenode;
typedef Treenode* Bintree;
Bintree Insert(Bintree,int);
void PrintTree(Bintree);
void Swap(int*,int*);
using namespace std;
int main(void){
clock_t start,finish;
start=clock();
int i=0,N=0;
Bintree root=nullptr;
srand((int)time(0));
cout<<"Input number."<<endl;
cin>>N;
int SrandBintree[N];
for(i=0;i<N;i++) SrandBintree[i]=i+1;
for(i=N-1;i>0;i--) Swap(&SrandBintree[i],&SrandBintree[rand()%i]);
for(i=0;i<N;i++) root=Insert(root,SrandBintree[i]);
PrintTree(root);
finish=clock();
cout<<endl<<endl<<"the time cost is:" << double(finish - start) / CLOCKS_PER_SEC<<endl;
return 0;
}
void Swap(int* x,int* y){
int temp=0;
temp=*x;
*x=*y;
*y=temp;
}
Bintree Insert(Bintree root,int x){
Bintree father=nullptr,p=root;
if(root==nullptr){
root=new struct Treenode;
root->data=x;
}else{
while(p){
father=p;
if(p->data>x) p=p->Left;
else if(p->data<x) p=p->Right;
else{
cout<<"Data collision."<<endl;
return root;
}
}
p=new struct Treenode;
p->data=x;
if(father->data>x) father->Left=p;
else father->Right=p;
}
return root;
}
void PrintTree(Bintree root){
stack<Bintree>str;
while(root||!str.empty()){
for(;root;root=root->Left) str.push(root);
if(!str.empty()){
root=str.top();
str.pop();
cout<<root->data<<endl;
root=root->Right;
}
}
}