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 (将#修改为@)