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   8

Output:

1

Explanation: 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

  1. Helper Function:

  • Define a helper function largestBSTHelper that returns information about whether the subtree is a BST, its size, and the minimum and maximum values in the subtree.

  1. Base Case:

  • If the current node is None, return Info(True, 0, float('inf'), float('-inf')).

  1. 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.

  1. 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.

  1. Return the Result:

  • The largestBst function returns the size of the largest BST in the tree by calling largestBSTHelper.

Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n), as each node is visited once.

  • Expected Auxiliary Space Complexity: O(h), where h is 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