c++ - 二叉搜索树 : Issue with Insert Function

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

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

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

最佳答案

尝试以下操作:

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

关于c++ - 二叉搜索树 : Issue with Insert Function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21889124/

相关文章:

在 C 中链接任务指针

c++ - 为什么线程从未作为 C++ 标准的一部分包含在内?

c++ - gdb 远程调试缓存远程目标

c++ - 将CComboBox添加到CMFCStatusBar Pane 的问题

php - PDO 未插入数据库

python - 将字符插入字符串到数字末尾

C 在链表开头插入元素

c++ - 从纯虚拟(接口(interface))类虚拟继承是一个很好的约定吗?

C、函数格式化中的结构指针

c - 该程序中的内存是如何分配的?