Ram 空间在创建包含 60000 个元素的二叉搜索树时耗尽

Ram space exhausted while creating a Binary Search Tree of 60000 elements

本文关键字:搜索树 元素 空间 创建 包含 60000 Ram      更新时间:2023-10-16

我正在尝试构建一个巨大的二叉搜索树:

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;
    }
}