Here is my code where I am assigning values to node of tree. I am able to assign well till right and left child of tree. But when I try to use left->left child of root, it gives me access violation error.
Unhandled exception at 0x00DE5CC3 in Trees.exe: 0xC0000005: Access violation reading location 0x00000004.
Exactly getting error at line, unique_ptr<node> (r->left->left) = newNode(4);
.
I am using unique_ptr
, if I use raw pointers, everything works as expected.
Following is my code,
using std::cout;
using std::endl;
using std::unique_ptr;
struct node
{
int data;
node * left;
node * right;
};
unique_ptr<node> newNode (int i)
{
unique_ptr<node> n (new node);
n->data = i;
n->left = nullptr;
n->right = nullptr;
return n;
}
int main(int argc, char* argv[])
{
unique_ptr<node> r = newNode(1);
unique_ptr<node> (r->left) = newNode(2);
unique_ptr<node> (r->right) = newNode(3);
unique_ptr<node> (r->left->left) = newNode(4);//this line craches
unique_ptr<node> (r->left->right) = newNode(5);
return 0;
}