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 node represents a binary search tree and there are total 7 nodes.
11 / \ 8 10 / / \ 5 9 8 / \ 4 6
Sub-tree rooted under node 5 is a BST5 / \ 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 varible num_BST to store the number of Binary search tree rooted under the current node.
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.
- Total number of possible Binary Search Trees and Binary Trees with n keys
- Minimum swap required to convert binary tree to binary search tree
- Total number of possible Binary Search Trees using Catalan Number
- Find maximum count of duplicate nodes in a Binary Search Tree
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Number of pairs with a given sum in a Binary Search Tree
- Binary Tree to Binary Search Tree Conversion
- Binary Tree to Binary Search Tree Conversion using STL set
- Difference between Binary Tree and Binary Search Tree
- Merge Two Balanced Binary Search Trees
- Self-Balancing-Binary-Search-Trees (Comparisons)
- Check whether the two Binary Search Trees are Identical or Not
- Print Common Nodes in Two Binary Search Trees
- Prime Numbers present at Kth level of a Binary Tree
- Count the number of visible nodes in Binary Tree
- Find the numbers present at Kth level of a Fibonacci Binary Tree
- Count the number of paths from root to leaf of a Binary tree with given XOR value
- Binary Search Tree | Set 1 (Search and Insertion)
- Convert a Binary Search Tree into a Skewed tree in increasing or decreasing order
- Floor in Binary Search Tree (BST)
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.