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 the largest BST is 2
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 firstname.lastname@example.org. 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.