c++ - 二叉树的示例实现不适用于大量值

标签 c++ c algorithm data-structures

我最近尝试实现一个二叉树,它似乎适用于少于 1000 个值,但在那之后最终它给我堆栈溢出错误

#include<iostream>
#include<math.h>

using namespace std;
struct Node{
    long long int val;
    Node *left;
    Node *right;
};
struct BinaryTree{
    Node *head  = (Node*) malloc(sizeof(Node));
    bool headSet = false;
    Node* findLast(Node *asgn,int val){
        if (val > asgn->val){
            if (asgn->right != NULL)
                asgn  = findLast(asgn->right, val);
            else
                return asgn;
        }
        else{
            if (asgn->left != NULL)
                asgn = findLast(asgn->left, val);
            else
                return asgn;
        }
        return asgn;
    }
    void insert(long long int vals){
        if (headSet){
            Node *asgn = (Node*) malloc(sizeof(Node));
            asgn = findLast(head,vals);
            Node *fix = (Node*)malloc(sizeof(Node));
            fix->val = vals;
            fix->left = NULL;
            fix->right = NULL;
            if (vals > asgn->val){
                asgn->right = fix;
                asgn->left = NULL;
            }
            else{
                asgn->right = NULL;
                asgn->left = fix;
            }
        }
        else{
            head->val = vals;
            head->right = NULL;
            head->left = NULL;
            headSet = true;
        }
    }
};
int main(){
    BinaryTree a;
    for (long long int i = 0; i < 100;i++)
    a.insert(i);

    return 0;
}

例如:- 如果我改变

for (long long int i = 0; i < 100;i++)
    a.insert(i);

for (long long int i = 0; i < 10000;i++)
    a.insert(i);

它给我错误。我似乎无法理解为什么会发生这种情况,堆栈在哪里溢出?

最佳答案

您的堆栈溢出来自您的 findLast 方法,一旦二叉树变得太大,递归就会变得太多并在某一点溢出调用堆栈。您应该通过将有关搜索的信息存储在某种结构中并动态分配它来将其转换为非递归方法,这样您的堆栈就不会填满。

P.S 在 C++ 中使用 new 而不是 mallocdelete 来清除分配的内存,你目前正在泄漏内存。

关于c++ - 二叉树的示例实现不适用于大量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39916093/

相关文章:

c - 用于定期监听同一本地主机上的多个进程的最佳进程间消息传递模式

c# - 将 C printf(%c) 转换为 C#

Python:判断数字是否为正方形、立方体等的函数

在树中找到最大的 n 个节点的算法

c++ - 延迟评估和/或灵活的宏名称

c++ - 从 C++ 类模板中的函数调用另一个成员函数

c++ - 为什么 gcc 和 clang 会为 std::find 生成这么多代码?

计算中的 C 结构

c# - 二进制搜索算法随机生成的数组项不起作用

c++ - 六边形网格算法