Given a Binary tree and number of nodes in the tree, the task is to find the number of pairs violating the BST property. Binary Search Tree is a node-based binary tree data structure which has the following properties:
- The left subtree of a node contains only nodes with keys lesser than the node’s key.
- The right subtree of a node contains only nodes with keys greater than the node’s key.
- The left and right subtree each must also be a binary search tree.
Input: 4 / \ 5 6 Output: 1 For the above binary tree, pair (5, 4) violate the BST property. Thus, count of pairs violating BST property is 1. Input: 50 / \ 30 60 / \ / \ 20 25 10 40 Output: 7 For the above binary tree, pairs (20, 10), (25, 10), (30, 25), (30, 10), (50, 10), (50, 40), (60, 40) violate the BST property. Thus, count of pairs violating BST property is 7.
- Store the inorder traversal of the binary tree in an array.
- Now count all the pairs such that a[i] > a[j] for i < j which is number of inversions in the array.
- Print the count of pairs violating BST property.
Below is the implementation of the above approach:
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Count number of pairs (i, j) such that arr[i] * arr[j] > arr[i] + arr[j]
- Count of even and odd power pairs in an Array
- Count pairs from two BSTs whose sum is equal to a given value x
- Count pairs with Bitwise-AND as even number
- Count pairs with Bitwise XOR as EVEN number
- Count pairs in an array that hold i*arr[i] > j*arr[j]
- Count unequal element pairs from the given Array
- Count all pairs of adjacent nodes whose XOR is an odd number
- Count pairs in a binary tree whose sum is equal to a given value x
- Count pairs in an array which have at least one digit common
- Count possible combinations of pairs with adjacent elements from first N numbers
- Ways to form n/2 pairs such that difference of pairs is minimum
- Minimum count of Full Binary Trees such that the count of leaves is N
- Sets of pairs in C++
- CSS | transition-property Property
- How to create an unordered_map of pairs in C++?
- How to create an array with key value pairs in PHP?
- Number of special pairs possible from the given two numbers
- Number of pairs with Pandigital Concatenation
- Print all pairs from two BSTs whose sum is greater than the given value
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : Rajput-Ji