删除有两个孩子的目标

时间:2015-02-03 23:10:50

标签: c++ c pointers binary-tree binary-search-tree

有人会介意简要解释为什么我不断从这段代码中获得分段错误吗?

“target”是要删除的节点,我正在尝试将其替换为左侧分支上最右边的叶子。 “父母”是目标的父母。

    else if (target->left != NULL && target->right != NULL) {
      Node * childishDad = target;
      Node * childish = target->left;

      while(childish->right != NULL){
        childishDad = childish;
        childish = childish->right;
      }
      if(parent->left == target)
        parent->left = childish;

      if(parent->right == target)
        parent->right = childish;

      childish->left = target->left;
      childish->right = target->right;

      if(childishDad != target)
        childishDad->right = NULL;

      delete target;
      return true;
    }

2 个答案:

答案 0 :(得分:0)

当while循环完成时,你知道

childish->right == NULL

但是,稍后你分配

childish->right = target->right;

也许这就是问题所在。

答案 1 :(得分:0)

我意识到我没有检查parent == NULL,所以在尝试删除根节点的情况下失败了。