B ++中的BST,添加节点时返回true或false

问题描述

我正在学习C ++。

我想将BST中add函数的返回类型设置为bool,如果树中已经存在相同的项目,则返回true,而将其添加到树中时返回false。

这是代码,关于如何实现此目标的任何建议?

节点类(.h文件)中的代码

node* insert(string content,node* t)
{
    if(t == NULL)
    {
        t = new node;
        t->data = content;
        t->left = t->right = NULL;
    }
    else if(content < t->data)
        t->left = insert(content,t->left);
    else if(content > t->data)
        t->right = insert(content,t->right);
    return t;
}

.cpp文件中的代码

BST :: BST() {
    root = NULL;
}

void BST :: add(string content) {
    root = insert(content,root);
}

有什么建议吗?这段代码也是从BST Implementation in C++

引用的

解决方法

最简单的方法是进行搜索,以标识要插入的父节点。我可以向您显示元组,但现在更简单的是使用out参数来指示“树中已有值”的条件是否为out参数。

    Element discountDate = doc.selectFirst("div.price-availability");