时间在二叉搜索树中返回 0

Time returns 0 in Binary Search Tree

本文关键字:返回 搜索树 时间      更新时间:2023-10-16

我想测量搜索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;
}

如果参数nodeNULL,则insert函数不会返回任何内容。这是未定义的行为,实际上可能导致任何事情,包括恶魔从你的鼻子里飞出来。

看到没有发生段错误,编译器似乎优雅地将NULL分配给 main 中的指针root,这意味着您的树最多有两个元素(并且内存中丢失了很多很多这样的树)。在两个元素树中搜索元素当然可能需要 0 秒。但这只是随机猜测——它是 UB,它可以是一切。


您应该启用编译器警告(对于gcc例如标志-Wall-Wextra-pedantic,最好是带有将所有警告转换为错误的-Werror)。使用编译器警告很容易找到此类问题。