1

The problem

I'm having some doubts with my insertion method in C++, it causes a stack overflow.

Compiled with g++ on Windows

g++ -Wall -O2 Tree.cpp -o Tree

Output

0 [unknown (0x2B70)] Tree 10496 cygwin_exception::open_stackdumpfile: Dumping stack trace to Tree.exe.stackdump

Code

# 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;
}
3
  • looks like infinite recursion to me Commented Jul 22, 2016 at 16:15
  • This is because return node should be added to the if for the base case. Commented Jul 22, 2016 at 16:16
  • Yes it was a infinite recursion hehe, thanks :) Commented Jul 22, 2016 at 16:30

2 Answers 2

2

You have to stop recursion when it reached to NULL.

Try this:

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;

}
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, Now it works, I'm new in recursion :), Thanks for your time.
0
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);

1 Comment

Thanks for explaining , recursion is a bit confusing at the beginning, this condition apply in all the recursive methods? For example, count the number of nodes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.