Given a Binary Tree, write a function that returns the size of the largest subtree which is also a Binary Search Tree (BST). If the complete Binary Tree is BST, then return the size of the whole tree.
Input: 5 / \ 2 4 / \ 1 3 Output: 3 The following subtree is the maximum size BST subtree 2 / \ 1 3 Input: 50 / \ 30 60 / \ / \ 5 20 45 70 / \ 65 80 Output: 5 The following subtree is the maximum size BST subtree 60 / \ 45 70 / \ 65 80
We have discussed two methods in below post.
Find the largest BST subtree in a given Binary Tree | Set 1
In this post, a different O(n) solution is discussed. This solution is simpler than the solutions discussed above and works in O(n) time.
The idea is based on method 3 of check if a binary tree is BST article.
A Tree is BST if following is 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 return maximum and minimum values in subtree rooted with it. If any node follows above properties and size of
Size of largest BST is 2
Time Complexity : O(n)
This article is contributed by Shubham Gupta. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Largest value in each level of Binary Tree
- Find the largest BST subtree in a given Binary Tree | Set 1
- Find the largest Complete Subtree in a given Binary Tree
- Find the largest Perfect Subtree in a given Binary Tree
- Largest value in each level of Binary Tree | Set-2 (Iterative Approach)
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Minimum swap required to convert binary tree to binary search tree
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
- Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
- Binary Tree to Binary Search Tree Conversion
- Binary Tree to Binary Search Tree Conversion using STL set
- Check whether a given binary tree is skewed binary tree or not?
- Check if a binary tree is subtree of another binary tree | Set 2
- Check if a binary tree is subtree of another binary tree | Set 1