gpt4 book ai didi

c++ - 来自 testdome 的二叉搜索树

转载 作者:行者123 更新时间:2023-11-28 01:46:55 29 4
gpt4 key购买 nike

我正在为 testdome https://www.testdome.com/for-developers/solve-question/9708 中给出的测试样本写答案

问题是关于二叉搜索树的:

二叉搜索树(BST)是一种二叉树,其中每个节点的值都大于或等于该节点左子树中所有节点中的值,并且小于该节点右子树中所有节点中的值.

编写一个函数来检查给定的二叉搜索树是否包含给定的值。

例如,对于下面的树:n1(值:1,左:空,右:空)n2(值:2,左:n1,右:n3)n3(值:3,左:空,右:空)调用 contains(n2, 3) 应该返回 true,因为根在 n2 的树包含数字 3。

enter image description here

我修改了下面的代码,输出看起来运行良好,但测试结果告诉一个失败存在: Performance test on a large tree: Time limit exceeded你能帮我修改一下模式来解决这个问题吗?

#include <stdexcept>
#include <string>
#include <iostream>

class Node
{
public:
Node(int value, Node* left, Node* right)
{
this->value = value;
this->left = left;
this->right = right;
}

int getValue() const
{
return value;
}

Node* getLeft() const
{
return left;
}

Node* getRight() const
{
return right;
}

private:
int value;
Node* left;
Node* right;
};

class BinarySearchTree
{
public:
static bool contains(const Node& root, int value)
{
Node* tree;
int val = root.getValue();
std::cout<<"current node's value is:"<<val<<'\n';

if (val==value)
{
return true;
}
else if (val>value)
{
tree = root.getLeft();
if(tree != NULL)
{
std::cout<<"left node's value is:"<<tree->getValue()<<'\n';
return contains(*tree, value);
}
else
{
return false;
}
}
else
{
tree = root.getRight();
if(tree != NULL)
{
std::cout<<"right node's value is:"<<tree->getValue()<<'\n';
return contains(*tree, value);
}
else
{
return false;
}
}
//throw std::logic_error("Waiting to be implemented");
}
};

#ifndef RunTests
int main()
{
Node n1(1, NULL, NULL);
Node n3(3, NULL, NULL);
Node n2(2, &n1, &n3);
std::cout << BinarySearchTree::contains(n2, 3);
}
#endif

最佳答案

删除 std::cout 即可。打印到终端需要大量时间。

关于c++ - 来自 testdome 的二叉搜索树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44688399/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com