簡體   English   中英

二叉樹插入方法導致堆棧溢出

[英]Binary tree insertion method causes stack overflow

問題

我對C ++中的插入方法有疑問,它會導致堆棧溢出。

在Windows上與g ++一起編譯

g ++-牆-O2 Tree.cpp -o樹

產量

0 [未知(0x2B70)]樹10496 cygwin_exception :: open_stackdumpfile:將堆棧跟蹤信息轉儲到Tree.exe.stackdump

# include < iostream >

using namespace std;

struct Node{

    int val;
    Node *left, *right;

};

Node* Insert(Node *node, int val)
{

    if(node == NULL)
    {
        node = new Node;
        node->val = val;
        node->right = node->left = NULL;
    }   

if(node->val > val)
    node->left = Insert(node->left, val);
else
    node->right = Insert(node->right, val);

return node;

}

int main()
{

Node *root = NULL; // New tree

root = Insert(root, 5);
root = Insert(root, 19);
root = Insert(root, 1);
root = Insert(root, 32);
return 0;
}

當到達NULL時,您必須停止遞歸。

嘗試這個:

Node* Insert(Node *node, int val)
{

    if(node == NULL)
    {
        node = new Node;
        node->val = val;
        node->right = node->left = NULL;
    }

    else if(node->val > val) // add "else" here
        node->left = Insert(node->left, val);
    else
        node->right = Insert(node->right, val);

    return node;

}
The problem in your function is, you are trying to access null memory. 
Please check my comments here

/* You are checking for node == null, which is correct. */
if(node == NULL)
    {
        node = new Node;
        node->val = val;
        node->right = node->left = NULL;
    }


    /* Consider what will happen when node is null, you are still trying to access null memory. You need to put else if here to avoid control to fall into this condition if node is null. */
    if(node->val > val) // add "else" here
        node->left = Insert(node->left, val);
    else
        node->right = Insert(node->right, val);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM