微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

BST中只有一个子节点时如何删除根节点?

如何解决BST中只有一个子节点时如何删除根节点?

#include <iostream>

using namespace std;

class BST {
  int data;
  BST *left,*right;
  public: 
    BST();
    BST(int);
    BST* Insert(BST*,int);
    void Delete(BST*,BST*,int);
    void Inorder(BST*);
};

BST::BST():data(0),left(NULL),right(NULL) {}

BST::BST(int value):BST() {
  data = value; 
}

BST* BST::Insert(BST *root,int value) {
  if(!root) {
    return new BST(value);
  }
  if(value > root->data) {
    root->right = Insert(root->right,value);
  } else {
    root->left = Insert(root->left,value);
  }
  return root;
}

void BST::Delete(BST *parent,BST *root,int value) {
  if(!root) {
    return;
  }
  if(root->data == value) {
    if(!root->left && !root->right) {
      if(parent) {
        if (parent->left == root) {
          parent->left = NULL;
        }
        else {
          parent->right = NULL;
        }
      }
      free(root);
      return;
    }
    if(!root->left || !root->right) {
      BST *child = root->left ? root->left : root->right;
      if(parent) {
        if (root == parent->left) {
          parent->left = child;
        }
        else {
          parent->right = child;
        }
        free(root);
      } else {
        // what do i have to do here ?
      }
      return;
    }
    BST *inorderSuccessor = root->right;
    parent = root;
    while (inorderSuccessor->left) {
      parent = inorderSuccessor;
      inorderSuccessor = inorderSuccessor->left;
    }
    root->data = inorderSuccessor->data;
    Delete(parent,inorderSuccessor,inorderSuccessor->data);
  }
  if(value > root->data) {
    Delete(root,root->right,value);
  } else {
    Delete(root,root->left,value);
  }
}

void BST::Inorder(BST *root) {
  if(!root) {
    return;
  }
  Inorder(root->left);
  cout << root->data << " ";
  Inorder(root->right);
}

int main() {
  BST bst,*root = NULL;
  root = bst.Insert(root,4);
  bst.Insert(root,2);
  // bst.Insert(root,5);
  bst.Insert(root,1);
  bst.Insert(root,3);
  bst.Delete(NULL,root,4);
  bst.Inorder(root);
  return 0;
}

当我做 free(root) 时,整个树都被删除了。 我已经完成了我所知道的几乎所有事情,但它只是无法正确运行。 我正在跟踪函数本身中的父节点。 我正在使用递归来做到这一点。如果 parent 为空,我可以告诉节点是树的根。 其他一切工作正常。我已经检查了所有其他情况。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。