实现我自己的二进制树

Implementing my own binary tree

本文关键字:二进制 自己的 我自己 实现      更新时间:2023-10-16

对于家庭作业,我必须实现一个二进制树(不使用STL二进制树)容器。除了一个外,我所有的树函数都在工作。

链接到我的代码:https://github.com/matthamil/BinaryTree

在bt_class.h中,我有一个带有模板实现的binary_tree模板类。

在bintree.h中,我有一个带有模板实现的binary_tree_node类。

在main.cpp中,我进行了一系列测试来确保函数正常工作。

我的问题在这里:

template <class Item>
Item binary_tree<Item>::retrieve( ) const
{
    return current_ptr->data();
}

我需要这个函数的返回类型是存储在binary_tree_node中的任何内容的数据类型。我不知道如何做到这一点。

对于当前实现,它返回一个指向当前节点的指针。

我应该能写

cout << test->retrieve();

在main.cpp中,输出将是当前节点的数据。然而,由于它返回了一个指针,我必须添加一个额外的步骤:

*first = test->retrieve();
cout << first->data() << endl;
//"first"

有人能帮忙吗?

我认为问题就在这里,add_left,add_right。

template <class Item>
void binary_tree<Item>::create_first_node(const Item& entry)
{
    if (count == 0)
    {
        root_ptr = new Item(entry);
        current_ptr = root_ptr;
        count++;
    } else {
        std::cout << "Can't create first node for tree that has a first node already." << std::endl;
    }
}

这里发生的情况是,您正在传递节点的指针并调用new。所以基本上你要做的是创建一个binary_tree_node(&binary_tree _node)。

binary_tree_node<string> *first = new binary_tree_node<string> ("first");
binary_tree_node<string> *second = new binary_tree_node<string> ("second");
binary_tree_node<string> *third = new binary_tree_node<string> ("third");
test->create_first_node(*first);
test->add_right(*second);
test->add_left(*third);

因此,在您的binary_tree_node中还有另一个binary_tee_node。有不同的方法可以修复它。修复它的最佳方法只是将指针分配给current_ptr,或者简单地在binary_tree_node中实现一个适当的复制构造函数。然而,正如评论已经解释的那样,这是一个糟糕的设计选择。类binary_tree应该在内部生成binary_tree_node类,而用户不必手动实例化这些类并处理这些指针。