【问题标题】:How to append a binary tree to another如何将二叉树附加到另一个
【发布时间】:2019-11-26 04:19:21
【问题描述】:

我正在编写一个函数,它应该附加一棵二叉树来替换另一棵树的节点。我将两棵树的根和要替换的节点的标识符传递给函数,但我不确定如何交换指向要删除的节点的指针的地址并将其设置为指向我要追加的树的根。

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 指向我正在检查的节点以检查它是否是我要替换的节点。 ptrApp 是我要追加的树的根。

【问题讨论】:

  • 你有向树中添加节点的函数吗?如果这样做,那为什么不遍历源树,对于每个节点,只需将其添加到目标树并利用代码重用?
  • 如何用树替换节点?节点子节点会发生什么,它们最终会在哪里?这对我来说毫无意义。

标签: c++ pointers recursion tree


【解决方案1】:

需要进行一些更改: 1. 添加一个返回值,以便您知道交换是否成功。 2. 在删除的子树上递归释放内存。

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);
        }
}

【讨论】:

  • 这是如何工作的? ptrMod=ptrApp; 什么都不做,因为 ptrMod 是一个局部变量。
猜你喜欢
  • 1970-01-01
  • 2015-12-20
  • 1970-01-01
  • 1970-01-01
  • 2014-09-24
  • 2012-06-06
  • 1970-01-01
  • 2021-08-24
  • 1970-01-01
相关资源
最近更新 更多