Skip to main content
LeetCode 333, Medium. Topics: Tree, Depth-First Search, Binary Search Tree, Dynamic Programming, Binary Tree. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 15 parametrized pytest cases, and a playground notebook:

Problem

Given the root of a binary tree, find the largest subtree, which is also a Binary Search Tree (BST), where the largest means subtree has the largest number of nodes. A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned properties:
  • The left subtree values are less than the value of their parent (root) node’s value.
  • The right subtree values are greater than the value of their parent (root) node’s value.
Note: A subtree must include all of its descendants.

Examples

Example 1

Constraints

  • The number of nodes in the tree is in the range [0, 10^4].
  • -10^4 <= Node.val <= 10^4
Follow up: Can you figure out ways to solve it with O(n) time complexity?

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026