【问题标题】:Implementing my own binary tree实现我自己的二叉树
【发布时间】:2015-12-04 02:06:08
【问题描述】:

对于家庭作业,我必须实现一个二叉树(不使用 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"

谁能提供帮助?

【问题讨论】:

  • 没有人会在链接上查看您的代码。请发帖MCVE
  • 如果你的树有当前节点,那么你犯了一个主要的设计错误。
  • 您将Itembinary_tree 的模板参数)设置为节点类型,而不是值类型。这是一个不寻常的选择,也许应该修复。如果你不解决这个问题,你对检索的定义可以使用 C++11 特性auto 来推断值类型,或者更复杂的模板编码可以使值类型显式。
  • 在你的树类和节点类中使用Item 具有Item 的两种不同含义是令人困惑的。我没有尝试构建您的代码,但我不希望它编译,因为该检索函数似乎在该类型的节点意义上返回 Item,但在树中声明为返回 Item感觉。

标签: c++ templates tree binary-tree


【解决方案1】:

我认为问题出在这里,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_tree_node。 有不同的方法来修复它。修复它的最佳方法是将指针分配给 current_ptr,或者只是在 binary_tree_node 中实现适当的复制构造函数。然而,正如 cmets 已经解释的那样,这是一个糟糕的设计选择。 binary_tree 类应该在内部生成 binary_tree_node 类,而无需用户手动实例化这些类并处理这些指针。

【讨论】:

    猜你喜欢
    • 2012-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-05
    • 2017-10-05
    相关资源
    最近更新 更多