I just started learning Binary Search Trees. I have been trying to fix a couple of errors since yesterday. I looked at the reference links but I can't figure out what I'm doing wrong.
The example below was copied from one of the slideshows provided to us by the lecturer but when I run it, I get the following errors:
C2672: 'Insert': no matching overloaded function found
C2784: 'void Insert(TreeNode *&,ItemType)': could not deduce template argument for 'TreeNode *&' from 'ItemType *'
Any help would be appreciated.
BinaryTree.h
#pragma once
using namespace std;
template<class ItemType>
struct TreeNode
{
ItemType info;
ItemType* left;
ItemType* right;
};
template<class ItemType>
class TreeType
{
public:
TreeType();
~TreeType();
void InsertItem(ItemType item);
private:
TreeNode<ItemType>* root;
};
template<class ItemType>
void Insert(TreeNode<ItemType>*& tree, ItemType item) // helper function
{
if (tree == NULL)
{ // insertion place found
tree = new TreeNode<ItemType>;
tree->right = NULL;
tree->left = NULL;
tree->info = item;
}
else if (item < tree->info)
Insert(tree->left, item); // insert in left subtree
else
Insert(tree->right, item); // insert in right subtree
}
template<class ItemType>
void TreeType<ItemType>::InsertItem(ItemType item) // member function
{
Insert(root, item);
}
Main.cpp
#include <iostream>
#include "BinaryTree.h"
using namespace std;
int main()
{
TreeType<int> MyTree;
MyTree.InsertItem(9);
}
using namespace std;
is always a risky choice at global scope, but it is particularly nasty in a header because it forces that risky choice on everyone including the header. You also want your headers to be internally consistent. BinaryTree.h lacks a header that definesNULL
, forcing an unnecessary ordering on files that include it. This leads to mystery bugs. Code works, someone makes an inconsequential change, and gets errors. – user4581301