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;
}
return nodeshould be added to theiffor the base case.