22(July) Largest BST
22. Largest BST
The problem can be found at the following link: Question Link
Problem Description
Given a binary tree, find the size of its largest subtree that is a Binary Search Tree (BST). Note: Here, size equals the number of nodes in the subtree.
Examples:
Input:
1
/ \
4 4
/ \
6 8Output:
1Explanation: There's no subtree with size greater than 1 that forms a BST. All the leaf nodes are BSTs with size equal to 1.
My Approach
Helper Function:
Define a helper function
largestBSTHelperthat returns information about whether the subtree is a BST, its size, and the minimum and maximum values in the subtree.
Base Case:
If the current node is
None, returnInfo(True, 0, float('inf'), float('-inf')).
Recursive Calculation:
Recursively calculate the information for the left and right subtrees.
If both subtrees are BSTs and the current node's value is greater than the maximum value in the left subtree and less than the minimum value in the right subtree, the current subtree is a BST.
Update Information:
If the current subtree is a BST, update its size and the minimum and maximum values.
Otherwise, the size is the maximum size of the left or right subtree.
Return the Result:
The
largestBstfunction returns the size of the largest BST in the tree by callinglargestBSTHelper.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), as each node is visited once.
Expected Auxiliary Space Complexity: O(h), where
his the height of the tree, due to the recursion stack.
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated