Here is what I did. In my program, the rank of an element is defined as 1+ (there are no elements that exceed this element). Here you can see that the element should not be present in the tree.
Algorithm for rank search:
1. In the tree structure, the absence of elements in the subtree, including the root, is tracked. Thus, the head of the tree will contain the complete elements in the tree.
2. Map the element to node, if it is smaller than node, then there are (1 + no.of elements in the right child element) that are larger than the key element. Add it to the generic and recursively search for the item in the left child.
3.If the element is larger than the root of the node, then just find the element recursively in the right child element (there is no need to add anything, since we neglect the left tree, in which all elements are smaller than the given key)
4. Build the algorithm when you find that the element has reached zero.
The given program returns no elements exceeding the given key. 1+ return value is a rank.
code snippet:
int AVLUtils::rank(Node *root,long long val) { int n_ele_greater=0; int rank =0; if(root == NULL) return 0; if(val < root->key) { n_ele_greater = 1+this->n_elements(root->right_child)+this->rank(root->left_child,val); } else if(val > root->key) { n_ele_greater=this->rank(root->right_child,val); } else if(val == root->key) { return(this->n_elements(root->right_child)); } return(n_ele_greater); }
Hope this helps :)
source share