In a txt file there are IDs and next to them there are their neighbours like this:
1 1
1 2
1 3
2 1
2 4
2 8
3 5
Using AVL trees I store the IDs in one AVL tree and for every ID in this AVL I make another AVL tree in which I store its neighbours.In the end I make another txt file that in every line has an ID , its number of neighbours and then its neighbours.Using the above example the output txt is :
1 3 1 2 3
2 2 1 4 8
3 1 5
I managed to make it work but the problem is that when I have many IDs the program gets very slow because I suspect there are too many IDs in the first AVL tree to search insert and balance everytime.Is there any shortcut to make it faster? Some of the functions I used :
Node* AVLTree::search(Node *node, int ID)
{
if(node == NULL)
{
return NULL;
}
if(node->ID == ID)
{
return node;
}
else if(node->ID < ID)
{
return search(node->right, ID);
}
else
{
return search(node->left, ID);
}
}
void AVLTree::balance(Node *&node)
{
if (node == NULL)
{
return;
}
int height_diff = heightDifference(node);
if (height_diff > 1)
{
if( heightDifference(node->left) > 0)
{
node = left_rotation(node);
}
else
{
node = left_right_rotation(node);
}
}
else if (height_diff < -1)
{
if (heightDifference(node->right) > 0)
{
node = right_left_rotation(node);
}
else
{
node = right_rotation(node);
}
}
balance(node->left);
balance(node->right);
}
Node* AVLTree::insert(Node *node, int ID)
{
if(node == NULL)
{
node = newNode(ID);
size++;
return node;
}
else if(node->ID > ID)
{
node->left = insert(node->left, ID);
balance(node);
}
else if(node->ID < ID)
{
node->right = insert(node->right, ID);
balance(node);
}
return node;
}
int AVLTree::height(Node *node)
{
if (node != NULL)
{
int leftHeight = height(node->left);
int rightHeight = height(node->right);
int maxHeight = max(leftHeight, rightHeight);
return maxHeight + 1;
}
else
{
return 0;
}
}
int AVLTree::heightDifference(Node *node)
{
int leftHeight = height(node->left);
int rightHeight = height(node->right);
return leftHeight - rightHeight;
}
O(log(n))
, so it shouldn't be slow unless it's huge amounts of data. What is the code forAVLTree::height_difference
(a naive implementation would beO(n)
and slow down everything) ? Can you do a bit of profiling to know which functions take the most time? \$\endgroup\$ – coyotte508 May 28 '16 at 21:04std::multimap<int, int>
and put the same data into it. It's (typically) implemented as a red-black tree instead of AVL, but they're similar enough that if you've implemented your AVL tree correctly, they should be fairly similar (e.g., within a factor of 2). \$\endgroup\$ – Jerry Coffin May 29 '16 at 14:55O(log(n))
for all operations (including insert). With youbalance()
being called at every level on the way out of an insert it looks way more complex than that. \$\endgroup\$ – Martin York May 29 '16 at 19:57