【问题标题】:BST in c++, return true or false when adding nodeC++中的BST,添加节点时返回true或false
【发布时间】:2020-10-08 20:35:00
【问题描述】:

我现在正在学习 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++

【问题讨论】:

标签: c++ data-structures binary-search-tree


【解决方案1】:

最简单的方法是进行搜索以识别要插入的父节点。我可以向您展示元组,但现在只使用一个 out 参数来指示“值已经在树中”的条件是否是一个 out 参数会更容易。

node* makeNode(const string& content)
{
    node* n = new node();        
    n->left = pNode->right = nullptr;
    n->data = content;
    return n;
}

node* BST::findLeafNode(const string& content, node* n, bool* alreadyExists)
{
    *alreadyExists= false;

    if (n == nullptr)
    {
       return nullptr; // this should only happen when root == nullptr
    }

    if (content == n->data)
    {
        *alreadyExists = true; // exact match
        return n;
    }

    if (content < n->data)
    {
        return (n->left ? findLeafNode(content, n->left) : n;
    }
    else
    {
        return (n->right ? findLeafNode(content, n->right) : n;
    }

}

bool BST::add(const string& content)
{
    bool alreadyExists = false;
    node* parent = findLeafNode(content, root, &alreadyExists);
    if (same)
    {
       return false;
    }
    node* n = makeNode(content);

    if (parent == nullptr)
    {
        root = n;
    }
    else
    {
        if (content < n->data)
        {
           n->left = n;
        }
        else
        {
           n->right = n;
        }
     }
     return true;
}

【讨论】:

    猜你喜欢
    • 2022-01-08
    • 1970-01-01
    • 2011-01-17
    • 2017-05-02
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多