为什么我的代码不允许在二进制搜索树中插入节点

Why my code do not allow me to insert a node inside the binary search tree?

本文关键字:搜索树 插入 节点 二进制 我的 代码 不允许 为什么      更新时间:2023-10-16

我试图从一个头实现(我不能更改),在那里我要实现二进制搜索树。我在实现Insert函数时遇到了一个问题。函数只接收字符串的值。但不知何故,我需要在没有节点参数的情况下向下移动树才能做到这一点。这怎么可能?

标题为:

class BSNode
{
public:
    BSNode(string data);
    BSNode(const BSNode& other);
    ~BSNode();
    void insert(string value);
    bool isLeaf() const;
    string getData() const;
    BSNode* getLeft()const ;
    BSNode* getRight() const; 
private:
    BSNode* _left;
    BSNode* _right;
    string _data;
};

实现是:

void BSNode::insert(string value)
{
    _data.clear();
    _data.assign(value);
}

BSNode::BSNode(string data)
{
    _data.clear();
    _data.assign(data);
    _right = NULL;
    _left = NULL;
}

BSNode::BSNode(const BSNode& other)
{
    _data.clear();
    _data.assign(other._data);
    _right = other._right;
    _left = other._left;
}

从https://en.wikipedia.org/wiki/Binary_search_tree#Insertion,我认为您对BSNode::insert()的实现类似于:

void BSNode::insert(string value)
{
   if ( value < this->_data )
   {
      if ( _left != nullptr )
      {
         _left->insert(value);
      }
      else
      {
         _left = new BSNode(value);
      }
   }
   else if ( this->_data < value )
   {
      if ( _right != nullptr )
      {
         _right ->insert(value);
      }
      else
      {
         _right = new BSNode(value);
      }
   }
   else
   {
      // The value is already there. There is nothing to do.
   }
}