Problem solution · Python

Largest BST Subtree

Largest BST Subtree: a Python solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Depth-first search
Source
walkccc LeetCode Solutions
Length
28 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Depth-first search

For Largest BST Subtree, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. Combine child results or undo the choice when the branch finishes.

Code notes

  • 28 lines of Python from the credited upstream file 333.py.
  • The implementation keeps its working state in language-native values and containers.
  • No explicit loop blocks detected, together with recursive traversal.

Complexity

Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeLargest BST Subtree · PythonPython
Use this to learn the idea, then write your own version.
from dataclasses import dataclass  @dataclass(frozen=True)class T:  mn: int  # the minimum value in the subtree  mx: int  # the maximum value in the subtree  size: int  # the size of the subtree  class Solution:  def largestBSTSubtree(self, root: TreeNode | None) -> int:    def dfs(root: TreeNode | None) -> T:      if not root:        return T(math.inf, -math.inf, 0)       l = dfs(root.left)      r = dfs(root.right)       if l.mx < root.val < r.mn:        return T(min(l.mn, root.val), max(r.mx, root.val), 1 + l.size + r.size)       # Mark one as invalid, but still record the size of children.      # Return (-inf, inf) because no node will be > inf or < -inf.      return T(-math.inf, math.inf, max(l.size, r.size))     return dfs(root).size 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗