I implemented a binary tree in the following code. Its node's copy constructor and assignment operator should copy itself and all its descendents. Similarity a node's destructor should delete itself and all nodes descended from it.The print function just prints each node in a new line. How can I pretty-print it? Please point to errors(if any) and suggestions.
#include <iostream>
struct Node
{
Node(int);
Node(const Node&);
Node& operator=(const Node&);
~Node();
Node* left;
Node* right;
int value;
};
Node::Node(int v)
:left(nullptr),
right(nullptr),
value(v)
{}
Node::Node(const Node& other)
:left(nullptr),
right(nullptr),
value(other.value)
{
if (other.left != nullptr )
{
left = new Node(*other.left);
}
if (other.right != nullptr)
{
right = new Node(*other.right);
}
}
Node& Node::operator=(const Node& other)
{
value = other.value;
Node * left_orig = left;
left = new Node(*other.left);
delete left_orig;
Node * right_orig = right;
right = new Node(*other.right);
delete right_orig;
return *this;
}
Node::~Node()
{
if (left != nullptr )
{
delete left;
}
if (right != nullptr)
{
delete right;
}
}
Node* make_copy(Node* other)
{
Node * new_node = new Node(*other); // copy constructor invoked
return new_node;
}
void print(Node* n)
{
if (n == nullptr)
{
return;
}
std::cout << n << std::endl;
print(n->left);
print(n->right);
}
int main()
{
Node* n = new Node(1);
n->left = new Node(2);
n->right = new Node(3);
n->left->left = new Node(4);
n->left->right = new Node(5);
n->right->left = new Node(6);
n->right->right = new Node(7);
print(n);
auto nc = make_copy(n);
print(nc);
}
std::shared_ptr<T>
instead of raw pointers - you will not need to implement your own destructor in that case. – Ryan May 19 '15 at 5:28