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.
Input:11 / \ 8 10 / / \ 5 9 8 / \ 4 6
We know that a single node represents a BST and since here 8
nodes are present they all are BSTs.Also a subtree rooted under node 5 is a BST5 / \ 4 6
Another BST we have is rooted under the node 88 / 5 / \ 4 6
Thus total 10 BSTs are present.
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
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Binary Tree to Binary Search Tree Conversion using STL set
- Binary Tree to Binary Search Tree Conversion
- Check whether the two Binary Search Trees are Identical or Not
- Self-Balancing-Binary-Search-Trees (Comparisons)
- Merge Two Balanced Binary Search Trees
- Print Common Nodes in Two Binary Search Trees
- Binary Search Tree | Set 1 (Search and Insertion)
- Make Binary Search Tree
- Iterative Search for a key 'x' in Binary Tree
- Binary Search Tree | Set 2 (Delete)
- Floor in Binary Search Tree (BST)
- Optimal Binary Search Tree | DP-24
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.