学习随记三十八——生成N个结点的随机二叉查找树并计算时间

生成N个结点的随机二叉查找树

完成这个程序需要三个主要功能实现,生成N个随机结点,生成一颗二叉查找树储存这N个结点,计算程序运行时间。

  1. 生成N个随机的结点:
    我采用的方法是生成一个数组,数组按序存储,然后生成伪随机数交换数组元素即可
  2. 实现二叉查找树:
    因为我不想使用二级指针,所以我在设计的时候每次返回根结点地址,若根结点为空则为其开辟一个结点空间使其数据域储存待插入元素,若非空则每次使用一个结点指针记录结点地址循环定位到合适位置生成一个结点储存待插入元素,然后使新生成的结点为结点指针保存的结点的子结点即可。
  3. 计算程序运行时间:
    先定义两个类型为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;
		}
	}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值