-
Crashing
Hello,
First of all, this is my code:
Code:
#include <iostream>
using namespace std;
struct TreeNode
{
int data;
struct TreeNode *left;
struct TreeNode *right;
TreeNode() { left = NULL; right = NULL; }
};
void insertNode(int data, TreeNode* t)
{
if(data <= t->data)
{
// insert left
if(t->left == NULL)
{
cout << "INSERTING LEFT OF " << t->data << endl << endl;
TreeNode newt;
newt.data = data;
t->left = &newt;
}
else
insertNode(data, t->left);
}
else
{
// insert right
if(t->right == NULL)
{
cout << "INSERTING RIGHT OF " << t->data << endl << endl;
TreeNode newt;
newt.data = data;
t->right = &newt;
}
else
insertNode(data, t->right);
}
}
int main()
{
TreeNode a;
TreeNode b;
TreeNode c;
a.data = 5;
b.data = 50;
c.data = 20;
a.right = &b;
b.left = &c;
insertNode(80, &a);
cout << "The right child of the new node is: " << b.right->right << endl;
cout << b.right->right << endl << endl;
if(b.right->right == NULL)
cout << "ITS NULL";
else
cout << "ITS... NOT";
return 0;
}
I've just started out with C++ and I'm playing with binary trees. In InsertNode(), a new Node with the data 80 is added to the right of the 'b' node, meaning that b.right is that new node. Now, when displaying b.right->right (which should be NULL), I'm getting some weird stuff.
The first cout (starting with 'the right child of...') gives me a memory address, the second cout gives me 0. When checking if b.right->right == NULL, I get the message that it's not.
Why is this happening? When I create a new node, both the children are instantiated to NULL but apparently something goes wrong when I do this in the InsertNode() function.
-
You are allocating your treenodes on the stack. The pointers you keep to them are invalid the moment they are destructed (when if(t->right/left == NULL) closes).
In code:
Code:
// insert right
if(t->right == NULL)
{
cout << "INSERTING RIGHT OF " << t->data << endl << endl;
TreeNode newt;
newt.data = data;
t->right = &newt;
} // newt is destructed here, and t->right now points to invalid memory.
More than likely, you must dynamically allocate them. Research 'new' and 'delete'