【问题标题】:Binary Search Tree: Issue with Insert Function二叉搜索树:插入函数的问题
【发布时间】:2014-02-19 18:24:16
【问题描述】:

我一直在研究如何创建二叉搜索树,但在尝试创建自己的搜索树时遇到了问题。我必须使用以下私有结构来创建树。我看过的每个示例都使用指向结构的左右指针,我必须使用指向模板类的左右指针。我一直试图弄清楚如何编写插入函数以将新节点添加到我的树中,但由于这两个指针的设置方式,我一直遇到问题。有没有人知道如何使它与下面的这两个指针一起工作?

private:
struct BinaryNode
{
    Comparable element;
    BinarySearchTree<Comparable> *left;
    BinarySearchTree<Comparable> *right;
};
 BinaryNode *root;
};

这是我的构造函数

BinarySearchTree<Comparable>::BinarySearchTree() {
BinaryNode *temp;
temp = new BinaryNode;

temp->left= NULL;
temp->right= NULL;

root = temp;
}

【问题讨论】:

  • 建议创建一个新节点是没有意义的直到你有数据要插入是否有帮助? IE。当它为空时,你的树的根指针应该是nullptr

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


【解决方案1】:

尝试以下方法:

public:
    template <typename Comparable>
    void insert(const Comparable& key)
    {
        root = insert(root, key);
    }

private:
    template <typename Comparable>
    BinaryNode* insert(BinaryNode*& current_node, const Comparable& key)
    {
        if (current_node == nullptr)
        {
            // Create a leaf node and return it, thus attaching
            // it to the node we last called the function with

            return new BinaryNode{key, nullptr, nullptr};
        }

        if (key == current_node->element)
            // duplicate element, take some action
        else if (key < current_node->element)
            current_node->left = insert(current_node->left, key);
        else
            current_node->right = insert(current_node->right, key);

        return current_node;
    }

【讨论】:

  • 您需要将insert(BinaryNode* 更改为insert(BinaryNode*&amp;,否则这将不起作用。
  • 感谢您的回复。您的代码看起来可以正常工作,但问题是您将指针传递给插入函数中的节点。我会假设每当我调用插入函数时我都必须将 root 作为该指针传递,对吗?那么 root 在我班级的私人部分中,所以我将如何访问它以最初调用此函数?
  • @James 看看我在public 标签中定义的函数:这​​是您的用户将使用的函数,它将委托给private 部分中定义的函数。你只需说my_tree.insert(45),一切都会完成。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多