C ++将已删除节点的子节点移动到树中的父节点

时间:2017-10-17 00:57:59

标签: c++ linked-list tree

为节点实现了一个C ++类,但是在删除节点时我仍然会收到错误。

一般算法如下:

  • 将子级的parent_设置为parent_
  • 将孩子添加到父母的子女
  • 从此节点的子节点中删除子节目

这是我的班级文件:

template <typename E>
class TNode{

   ...

bool remove(){
            if ((parent_==NULL) && (children_.size()>0)){
                cout << "can't remove the root if it has children\n";
                return false;
            }
            else{

                parent_->children_.erase(std::remove(parent_->children_.begin(), parent_->children_.end(), this), parent_->children_.end());

                for (int i=children_.size()-1;i>=0; i--){

                    //my error is happening here

                    parent_ = parent_ -> children_;
                    this = children_ -> this;
                    parent_ = parent_ -> this;
                }

                //delete (deallocate memory of) this node
                delete this;
                return true;
            }
        }

        friend class gTree<E>;

      private:
        E data_;
        gTNode<E>* parent_;
        std::vector<gTNode<E>*> children_;
    };

有人能指出我正确的方向吗?

编辑错误是这样的:

gTree.h: In member function ‘bool gTNode<E>::remove()’:
gTree.h:50:29: error: expected unqualified-id before ‘this’
         this = children_ -> this;
                             ^
gTree.h:50:29: error: expected ‘;’ before ‘this’
gTree.h:51:30: error: expected unqualified-id before ‘this’
         parent_ = parent_ -> this;
                              ^
gTree.h:51:30: error: expected ‘;’ before ‘this’

1 个答案:

答案 0 :(得分:0)

实施完全错了。我在这段代码中看到了几个错误。像remove()在没有子节点的根节点上调用时访问NULL parent_一样。并且循环没有正确地解释vector::size()是无符号的。只是一般的语法错误。

尝试更像这样的东西:

template <typename E>
class gTNode
{
    ...
    bool remove()
    {
        if (parent_)
        {
            auto iter = std::find(parent_->children_.begin(), parent_->children_.end(), this);
            auto index = std::distance(parent_->children_.begin(), iter);
            parent_->children_.erase(iter);
            if (!children_.empty())
            {
                parent_->children.reserve(parent_->children_.size() + children_.size());
                parent_->children_.insert(parent_->children.begin() + index, children_.begin(), children_.end());
                for (auto *child : children_)
                    child->parent_ = parent_;
                children_.clear();
            }
        }       
        else if (!children_.empty())
        {
            cout << "can't remove the root if it has children\n";
            return false;
        }

        //delete (deallocate memory of) this node
        delete this;
        return true;
    }

    friend class gTree<E>;

private:
    E data_;
    gTNode<E>* parent_;
    std::vector<gTNode<E>*> children_;
};