In fact, I think we can directly use the copy constructor to recursively deep copy the tree. Suppose a class is defined as follows:
class TreeNode { public: TreeNode() : value(), count(0), left(nullptr), right(nullptr) {} TreeNode(const TreeNode &); ~TreeNode(); TreeNode &operator=(const TreeNode &);
Then copy constructor
TreeNode::TreeNode(const TreeNode &n) : value(n.value), count(n.count), left(nullptr), right(nullptr) { if (n.left) left = new TreeNode(*n.left);
Recursion will stop on the node sheet, as both of its children are nullptr
.
And the destructor too.
TreeNode::~TreeNode() { delete left; // recursively call destructor on left subtree node delete right; // recursively call destructor on right subtree node }
When left
or right
is nullptr
, delete
do nothing, so the recursion will stop.
You can see the full code here .
Jaege source share