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 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.
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Total number of possible Binary Search Trees using Catalan Number
- Binary Tree to Binary Search Tree Conversion
- Minimum swap required to convert binary tree to binary search tree
- Binary Tree to Binary Search Tree Conversion using STL set
- Difference between Binary Tree and Binary Search Tree
- Convert a Binary Search Tree into a Skewed tree in increasing or decreasing order
- Print Common Nodes in Two Binary Search Trees
- Check whether the two Binary Search Trees are Identical or Not
- Prime Numbers present at Kth level of a Binary Tree
- Find the numbers present at Kth level of a Fibonacci Binary Tree
- Construct a Maximum Binary Tree from two given Binary Trees
- Find maximum count of duplicate nodes in a Binary Search Tree
- Count permutations of given array that generates the same Binary Search Tree (BST)
- Minimum count of Full Binary Trees such that the count of leaves is N
- Number of pairs with a given sum in a Binary Search Tree
- Generic Trees(N-array Trees)
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- 2-3 Trees | (Search and Insert)
- m-WAY Search Trees | Set-1 ( Searching )
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.