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:
- Count number of pairs (i, j) such that arr[i] * arr[j] > arr[i] + arr[j]
- Count pairs in an array that hold i*arr[i] > j*arr[j]
- 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 which have at least one digit common
- Count pairs in a binary tree whose sum is equal to a given value x
- Count all pairs of adjacent nodes whose XOR is an odd number
- 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++
- 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
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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