AVL tree functions "SELECT" and "RANK"

Evening, all. I'm trying to design a program that takes an input file with commands and integers, and uses those to build and manipulate an AVL tree. For the most part, it's working for me, however I'm hanging up on two functions. One is called RANK, and it basically says how many nodes have keys of a lower value than a given x.

The other is called SELECT, and it returns the element with the ith smallest key in the array. I know that these can somehow be manipulated using a traversal, but that's tripping me up in the implementation. Any help would be greatly appreciated. These are the functions as I have them now.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//Rank
int avl::rank(int i, nodeptr &n)
{
	if(n->rank>i)
	{	rank(i, n->left);	}
	else if(n->rank<i)
	{	rank(i, n->right);	}
	else if(n->rank==i)
	{	return n->element;	}
	else
		return -1;

}
//Select
nodeptr avl::sel(nodeptr &x, int i)
{
	if (x == NULL)
	{	return x;	} 
	if(x->left->rank >= i)
	{	return sel(x->left,i);	}
	if(x->left->rank +1 == i)
	{	return x;	}
	return sel(x->right,i-1-(x->left->rank));
}


And if anyone can point out what I might be doing wrong here, are well...

1
2
3
4
5
6
7
8
9
10
11
12
13
// Inorder Traversal
void avl::trav(nodeptr n, int i)
{
	cout<<"Trav";
	if (n!=NULL)
	{
		trav(n->left, i);
		n->rank=i;
		i++;
		cout<<"Travelling";
		trav(n->right, i);
	}
}
Topic archived. No new replies allowed.