bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 333. Largest BST Subtree

333. Largest BST Subtree

Leetcode Solutions

Post-Order Traversal to Find Largest BST Subtree

  1. Define a helper function that returns a tuple with four elements: isBST (boolean), size (int), min (int), and max (int).
  2. Perform a post-order traversal: first visit the left child, then the right child, and finally the current node.
  3. At each node, check if the left child is a BST and if the right child is a BST.
  4. If both children 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, then the current subtree is a BST.
  5. If the current subtree is a BST, calculate its size and update the maximum BST size if necessary.
  6. If the current subtree is not a BST, return a range that ensures the parent will not be a BST.
  7. After the traversal, return the maximum BST size found.
UML Thumbnail

Pre-Order Traversal to Find Largest BST Subtree

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...