Count greater nodes in AVL tree
In this article we will see that how to calculate number of elements which are greater than given value in AVL tree. Examples:
Input : x = 5 Root of below AVL tree 9 / \ 1 10 / \ \ 0 5 11 / / \ -1 2 6 Output : 4 Explanation: there are 4 values which are greater than 5 in AVL tree which are 6, 9, 10 and 11.
- We maintain an extra field ‘desc‘ for storing the number of descendant nodes for every node. Like for above example node having value 5 has a desc field value equal to 2.
- for calculating the number of nodes which are greater than given value we simply traverse the tree. While traversing three cases can occur:
- Case- x(given value) is greater than the value of current node. So, we go to the right child of the current node.
- Case- x is lesser than the value of current node. we increase the current count by number of successors of the right child of the current node and then again add two to the current count(one for the current node and one for the right child.). In this step first, we make sure that right child exists or not. Then we move to left child of current node.
- Case-x is equal to the value of current node. In this case we add the value of desc field of right child of current node to current count and then add one to it (for counting right child). Also in this case we see that right child exists or not. Calculating values of desc field
- Insertion – When we insert a node we increment one to child field of every predecessor of the new node. In the leftRotate and rightRotate functions we make appropriate changes in the value of child fields of nodes.
- Deletion – When we delete a node then we decrement one from every predecessor node of deleted node. Again, In the leftRotate and rightRotate functions we make appropriate changes in the value of child fields of nodes.
Preorder traversal of the constructed AVL tree is 9 1 0 -1 5 2 6 10 11 Number of elements greater than 9 are 2 Preorder traversal after deletion of 10 1 0 -1 9 5 2 6 11 Number of elements greater than 9 are 1
Time Complexity: Time complexity of CountGreater function is O(log(n)) where n is number of nodes in avl tree, as we are basically searching for the given number in avl which takes O(log(n)) time.
This article is contributed by Ashish Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.