Reputation: 11
I am implementing a Red black Tree where the insert function should have two templates, one for the item and the other for the key. I am passing the parameters in the insert function this way:
template <class Item, class Key>
void RedBlackTreeNode<Item, Key>::InsertKey(const Item *&T, const Key *&z)
I tried to pass an array(made up of random elements) in the second parameter, this way:
const int* pointer = &arr[i];
t1.InsertKey(//something else here// , pointer); //insert the tree and the node
However, I can't figure out what to pass as the first parameter in order to insert elements in the red black tree. What is the first parameter representing? I tried to pass the root of the tree, this way:
Node<int, int> n1;
t1.InsertKey(n1->root, pointer);
Unfortunately, this is not working.Any help please?
Thanks in advance.
Upvotes: 0
Views: 95
Reputation: 3778
If you're implementing a red black tree (or just even just a binary tree), you're insertion method just take the element to insert as parameter. You're inserting one Item
that can be compared to another item, there is no notion of Key
. If you want to create Key
/Value
container, you can just take an std::pair<Key, Value>
item and compare on item.first
, or something like this.
Here is a mock up of the code for the binary search tree insertion. You can start with that to add the properties that have to be kept for [red black tree insertion(http://en.wikipedia.org/wiki/Red%E2%80%93black_tree#Insertion):
template <class Item>
void BinarySearchTreeNode<Item>::Insert(Item item)
{
if (item < this->item)
{
if (this->leftChild == nullptr)
this->leftChild = new BinarySearchTreeNode(item);
else
insert(this->leftChild, item);
}
else
{
if (this->rightChild == nullptr)
this->rightChild = new BinarySearchTreeNode(item);
else
insert(this->rightChild, item);
}
}
And here a example usage (assuming the rest of the implementation has been done):
BinarySearchTree<int> tree;
tree.Insert(1); // Call insert on root node
Upvotes: 1