首页 > 解决方案 > C ++试图删除二叉树并将其移动到Vector

问题描述

所以我正在尝试编写一个函数,将二叉树的所有值放入一个向量中,稍后将使用该向量重新创建它。但是当我尝试调用这个函数时,我得到一个错误:

Error in `./bst': double free or corruption (fasttop):

这是我正在使用的功能。向量本身是一个包含节点的私有变量。size() 返回树的大小并且正在工作。

void BST::swapvector()
{
    Node *ptr = m_root;
    while (size() != 0)
    {
        if (ptr->m_left != NULL) {
            ptr = ptr->m_left;
        } else if (ptr->m_right != NULL) {
            ptr = ptr->m_right;
        } else {
            Node *temp = ptr;
            myvector.push_back(ptr); //starting from root, we traverse until we reach the bottom and then add ptr to the vector
            ptr = m_root;
            delete temp; //once we're finished, we delete temp
        }
    }
}

有谁知道为什么这不起作用?谢谢!

标签: c++binary-tree

解决方案


很明显为什么这不起作用。

    } else {
        Node *temp = ptr;
        myvector.push_back(ptr); //starting from root, we traverse until we reach the bottom and then add ptr to the vector
        ptr = m_root;
        delete temp; //once we're finished, we delete temp
    }

您将指针存储Node到向量中,然后Nodedelete temp. 之后存储到向量中的指针指向垃圾或不存在的内存。

“......一个将二叉树的所有值放入向量中的函数......” 不,您不是在存储二叉树值,而是在存储指向二叉树值(Node对象)的指针。

你可以做两件事:

  • 如果二叉树在其生命周期内不会被释放或更改,myvector那么您可以删除该delete temp;行。
  • 如果第一种情况的假设不正确,那么您需要将Node元素存储到向量中,而不是指向它们的指针。因此,定义myvectorvector<Node> myvector;代替vector<Node *> myvector;并更改myvector.push_back(ptr);myvector.push_back(*ptr);

推荐阅读