【问题标题】:Binary Search Tree - Deleting Node with no pointer to predecessor二叉搜索树 - 删除没有指向前任指针的节点
【发布时间】:2012-10-28 10:17:37
【问题描述】:

我有以下 BST 的实现:

struct BstNode
{
    int value;
    BstNode* leftSubnode;
    BstNode* rightSubnode;

    BstNode(int value)
    {
        this->value = value;
        this->leftSubnode = this->rightSubnode = nullptr;
    }
};

struct BstTree
{
    BstNode* root;
};

你可以看到,我没有指向前任(当前节点的父节点)的指针。我在实现添加/显示方法方面没有问题,但我不知道如何从我的结构中删除节点。当您只有左右节点的指针时,是否有可能做到这一点?请注意,所有方法都应该针对BstTree 结构实现,而不是针对BstNode 实现(因为我从老师那里收到的任务)。

【问题讨论】:

  • 您的数据结构中没有父指针,但没有理由在删除例程中没有父指针。

标签: c++ binary-search-tree


【解决方案1】:

类似这样,适应你的特殊要求并填空

void remove(BstTree& tree, int value)
{
   BstNode* parent = nullptr;
   BstNode* node = tree.root;
   while (node)
   {
      if (node->value == value)
      {
         if (parent)
         {
            // remove node using the parent pointer
         }
         else
         {
            // remove the root node
         }
         return;
      }
      if (value < node->value)
      {
         // go down left branch
         parent = node;
         node = node->leftSubNode;
      }
      else
      {
         // go down right branch
         parent = node;
         node = node->rightSubNode;
      }
   }
}

【讨论】:

    猜你喜欢
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多