Ram 空间在创建包含 60000 个元素的二叉搜索树时耗尽
Ram space exhausted while creating a Binary Search Tree of 60000 elements
我正在尝试构建一个巨大的二叉搜索树:
class Node
{
public:
int value;
shared_ptr<Node> left;
Node* right;
Node(int v):value(v){}
void addLeft(){
static int i;
shared_ptr<Node> node=make_shared<Node>(i);
left=node;
cout<<i++<<endl;
if(i<60000)
node->addLeft();
}
};
int main(){
shared_ptr<Node>root=make_shared<Node>(9);
root->addLeft();
return 0;
}
我在运行此代码时遇到 seg 错误,在 valgrind 中我有这份报告:
==17373== Stack overflow in thread #1: can't grow stack to 0xffe801000
关于如何在不溢出 RAM 空间的情况下构建 BST 的任何线索?
任何帮助都非常感谢
超出堆栈与超出 RAM 不同。函数调用累积在堆栈上,问题是您正在尝试在堆栈上放置 60000 个函数调用和变量。将你的函数转换为循环,你会没事的。它甚至会摆脱那个可怕的static int i
.
下面是使用没有递归的for
循环的函数版本。
void addLeft()
{
left = std::make_shared<Node>(0);
// tail is the last element to have been added to the tree
std::shared_ptr<Node> tail = left;
std::cout << 0 << std::endl;
// Add nodes from 1 to 60000 inclusively
for (int i = 1; i <= 60000; ++i)
{
std::cout << i << std::endl;
tail->left = std::make_shared<Node>(i);
tail = tail->left;
}
}
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- 正在尝试重载二进制搜索树分配运算符
- 使用C++创建特殊的二叉搜索树
- 在递归二叉搜索树中搜索
- 在二叉搜索树中插入新元素
- 删除二叉搜索树 (C++) 中的单个元素
- C++二叉搜索树实现不会添加每个元素
- 在二叉搜索树中查找元素
- 在C++中实现二叉搜索树,搜索不起作用.尝试打印节点的元素会导致输出崩溃
- Ram 空间在创建包含 60000 个元素的二叉搜索树时耗尽
- 如何在二叉搜索树中查找元素
- 在二进制搜索树中查找第二个最大元素
- n个元素上的二进制搜索树的数目
- 恢复两个元素错放的二叉搜索树
- 在二叉搜索树中查找第 n 个最小元素
- 如何在二叉搜索树节点中查找次要元素的平均值
- 二叉搜索树的第n个元素使用c++
- 在二进制搜索树中插入元素时出现Seg Fault 11
- 计数高度为h的二叉搜索树对n个元素的所有可能的根的个数
- 在二进制搜索树中插入元素时出错