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:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.