【发布时间】:2013-10-28 21:19:45
【问题描述】:
当我尝试将文件添加到这棵树时,它只会添加为树根的子节点。 比较运算符已正确重载(经过测试)。
有人能看出我的代码有什么明显错误吗?
template <typename Item>
void BTtree<Item>::addNode(const Item& newItem)
{
BTnode<Item> *newNode = new BTnode<Item>(newItem);
insert(newNode, root_ptr);
}
template <typename Item>
void BTtree<Item>::insert(BTnode<Item> *newNode, BTnode<Item> *root)
{
if(root == NULL)
{
root = newNode;
std::cout << "Flight added: ";
std::cout << *root << std::endl;
return;
}
else
{
if(newNode < root )
{
std::cout << "Adding "<<*newNode<< " left child of " << *root << std::endl;
insert(newNode, root->left() );
}
else
{
std::cout << "Adding "<<*newNode<<" right child of " << *root << std::endl;
insert(newNode, root->right());
}
}
}
编辑:为重载运算符提供代码
template <typename Item>
bool BTnode<Item>::operator < (const BTnode<Item>& other)
{
return ( *data < other.data );
}
对于我正在使用的对象
const bool Flight::operator < (const Flight& other) const
{
return ( (arrivalTimeHours < other.arrivalTimeHours) ||
(arrivalTimeHours == other.arrivalTimeHours &&
arrivalTimeMinutes < other.arrivalTimeMinutes)
);
【问题讨论】:
-
newNode < root比较两个指针。你想要的是比较两个BTnode<Item>s。指针比较是否适当重载? -
请附上您的重载运营商代码
-
奥斯瓦尔德,你是对的,我没有注意到这一点。我最初是在比较项目,但在我更改函数以将两个节点作为参数后重写了它但即使在比较项目时它也一样
标签: c++ templates recursion insert binary-search-tree