Question & Answer: Could someone explain each line in very detail…..

C++ BinaryTree

Could someone explain each line in very detail

IntBinaryTree::TreeNode *IntBinaryTree::copyTree(TreeNode *nPtr)
{
TreeNode *newNode;

if (nPtr == NULL)
{
return NULL;
}
else
{
newNode = new TreeNode;

newNode->value = nPtr->value;

newNode->left = copyTree(nPtr->left);

newNode->right = copyTree(nPtr->right);

return newNode;
}
}

also, why do we have a copy constructor and why do we add a destructor and a copy constructor in a program

Expert Answer

 

Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (!root){
return NULL;
}

TreeNode* res = new TreeNode(root->val);

if (root->right){
res->left = invertTree(root->right);
}else{
res->left = NULL;
}

if (root->left){
res->right = invertTree(root->left);
}else{
res->right = NULL;
}

return res;
}
};

Still stressed from student homework?
Get quality assistance from academic writers!