Given a binary tree, the task is to count the number of Binary Search Trees present in it.
Input:1 / \ 2 3 / \ / \ 4 5 6 7
Here each leaf node represents a binary search tree and there are total 4 nodes.
Input:11 / \ 8 10 / / \ 5 9 8 / \ 4 6
Sub-tree rooted under node 5 is a BST
5 / \ 4 6
Another BST we have is rooted under the node 88 / 5 / \ 4 6
Thus total 6 BSTs are present (including the leaf nodes).
Approach: A Binary Tree is a Binary Search Tree if the following are true for every node x.
- The largest value in left subtree (of x) is smaller than value of x.
- The smallest value in right subtree (of x) is greater than value of x.
We traverse tree in bottom up manner. For every traversed node, we store the information of maximum and minimum of that subtree, a variable isBST to store if it is a BST and variable num_BST to store the number of Binary search tree rooted under the current node.
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.