时间在二叉搜索树中返回 0
Time returns 0 in Binary Search Tree
我想测量搜索x所需的时间,问题是它总是0。我尝试使用不同的方法来计算时间,但没有运气。如果我计算插入,那么它可以正常工作,那么为什么在其他情况下它不起作用呢?
函数正常工作,因为它们取自解释 BST 的站点,我的任务是计算和分析完成函数所需的时间。
#include<iostream>
#include<cstdlib>
#include<ctime>
#include<windows.h>
#include <fstream>
#include <chrono>
#include <iomanip>
using namespace std;
struct node
{
int key;
struct node *left, *right;
};
struct node *newNode(int item)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
void inorder(struct node *root)
{
if (root != NULL)
{
inorder(root->left);
printf("%d ", root->key);
inorder(root->right);
}
}
struct node* insert(struct node* node, int key)
{
if (node == NULL)
return newNode(key);
if (key < node->key)
node->left = insert(node->left, key);
else
node->right = insert(node->right, key);
}
struct node * minValueNode(struct node* node)
{
struct node* current = node;
while (current->left != NULL)
current = current->left;
return current;
}
struct node* search(struct node* root, int key)
{
if (root == NULL || root->key == key)
return root;
if (root->key < key)
return search(root->right, key);
return search(root->left, key);
}
struct node* deleteNode(struct node* root, int key)
{
if (root == NULL)
return root;
if (key < root->key)
root->left = deleteNode(root->left, key);
else if (key > root->key)
root->right = deleteNode(root->right, key);
else
{
if (root->left == NULL)
{
struct node *temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL)
{
struct node *temp = root->left;
free(root);
return temp;
}
struct node* temp = minValueNode(root->right);
root->key = temp->key;
root->right = deleteNode(root->right, temp->key);
}
return root;
}
int main()
{
srand(time(NULL));
clock_t start;
struct node *root = NULL;
for(int i=0; i<400000; i++)
{
root = insert(root,((rand()*rand())%20000));
}
double duration;
start = std::clock();
root = search(root, 19999);
duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
cout << "Time: " << duration << endl;
return 0;
}
如果参数node
未NULL
,则insert
函数不会返回任何内容。这是未定义的行为,实际上可能导致任何事情,包括恶魔从你的鼻子里飞出来。
看到没有发生段错误,编译器似乎优雅地将NULL
分配给 main 中的指针root
,这意味着您的树最多有两个元素(并且内存中丢失了很多很多这样的树)。在两个元素树中搜索元素当然可能需要 0 秒。但这只是随机猜测——它是 UB,它可以是一切。
您应该启用编译器警告(对于gcc
例如标志-Wall
、-Wextra
和-pedantic
,最好是带有将所有警告转换为错误的-Werror
)。使用编译器警告很容易找到此类问题。
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- 正在尝试重载二进制搜索树分配运算符
- 使用C++创建特殊的二叉搜索树
- 在递归二叉搜索树中搜索
- 在二叉搜索树中插入时出现分段错误
- C++二叉搜索树模板从函数返回节点
- 我可以在没有堆栈的情况下在二叉搜索树中实现迭代器吗?
- 查找存储在二叉搜索树的所有非叶子中的数据总和?(返回整数的独立递归函数
- 返回二叉搜索树特定级别的节点数的函数
- 时间在二叉搜索树中返回 0
- 为什么这个计算二进制搜索树中节点的递归函数总是返回比预期更大的结果
- 我试图证明一个给定的树是一个二进制搜索树.我将输入一个二叉树,我只想让函数返回true
- Geany 在我的二叉搜索树结果的基础中返回奇怪的结果C++
- 二叉搜索树 (BST) 返回左子被视为函数,不理解
- 二叉搜索树 - 搜索函数返回对象 (C++)
- 搜索函数返回相同的,而不考虑二叉搜索树中存在的项目
- 函数,返回完整二进制搜索树底部级别中最右侧的节点
- 使用模板和unique_ptr实现的二叉搜索树中返回具有最小值的节点
- 二叉搜索树(搜索函数返回NULL)
- 从二叉搜索树C++返回引用