二进制搜索树:插入函数问题

时间:2014-02-19 18:24:17

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

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

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;
}

1 个答案:

答案 0 :(得分: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;
    }
相关问题