Q:

How to append a binary tree to another

i am coding a function which should append a binary tree replacing a node of another tree. I am passing to the function the root of the two trees and the identifier of the node i want to replace, but i am not sure how to swap the address of the pointer which points to the node that i want to remove and set it to point to the root of the tree i want to append.
void Tree::appendTree(TreeNode *ptrMod, TreeNode *ptrApp, string 
type_node) {
    if (ptrMod == nullptr) {
        return;
    }
    if (ptrMod->getType() == type_node) {
        delete(ptrMod);
        ptrMod=ptrApp;
    } else {
        appendTree(*(ptrMod->getLeftAddress()),ptrApp,type_node);
        appendTree(*(ptrMod->getRightAddress()),ptrApp,type_node);
    }
}

ptrMod points to the node i am inspecting to check if it the node i want to replace.
ptrApp is the root of the tree i want to append.

A:

Few changes needed: 1. Add a return value so you know if the swap was successful. 2. free memory recursively on the sub-tree deleted.
bool Tree::appendTree(TreeNode* & ptrMod, TreeNode* & ptrApp, string 
type_node) {
    if(ptrMod==nullptr)
    {
        return false; // did not swap
    }
    if(ptrMod->getType() == type_node){
        delete(ptrMod); // I hope you overloaded the delete operator to correctly delete all nodes of the tree
        ptrMod=ptrApp;
        return true; // swapped correctl;
        }
        else
        {
            if (appendTree(*(ptrMod->getLeftAddress()),ptrApp,type_node))
                return true;
            else return appendTree(*(ptrMod->getRightAddress()),ptrApp,type_node);
        }
}

