Given a binary tree, the task is to count the number of Binary Search Trees present in it.
1 / \ 2 3 / \ / \ 4 5 6 7
Here each node represents a binary search tree and there are total 7 nodes.
Input: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:
- 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
- Number of pairs with a given sum in a Binary Search Tree
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Difference between Binary Tree and Binary Search Tree
- Binary Tree to Binary Search Tree Conversion using STL set
- Binary Tree to Binary Search Tree Conversion
- Merge Two Balanced Binary Search Trees
- Check whether the two Binary Search Trees are Identical or Not
- Self-Balancing-Binary-Search-Trees (Comparisons)
- Prime Numbers present at Kth level of a Binary Tree
- Print Common Nodes in Two Binary Search Trees
- Binary Search Tree | Set 1 (Search and Insertion)
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.