Largest BST Subtree — LeetCode 333 Python Solution
- Problem
- #333
- Pattern
- Tree Traversal
- Reading time
- 4 min
- Source
- leetcode.com
The 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.
Example
- Input
- root = [10,5,15,1,8,null,7]
- Output
- 3
- Explanation
- The Largest BST Subtree in this case is the highlighted one. The return value is the subtree's size, which is 3.
Python solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def largestBSTSubtree(self, root: Optional[TreeNode]) -> int:
def dfs(root):
if root is None:
return inf, -inf, 0
lmi, lmx, ln = dfs(root.left)
rmi, rmx, rn = dfs(root.right)
nonlocal ans
if lmx < root.val < rmi:
ans = max(ans, ln + rn + 1)
return min(lmi, root.val), max(rmx, root.val), ln + rn + 1
return -inf, inf, 0
ans = 0
dfs(root)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 333. Largest BST Subtree is filed here because LeetCode tags it Tree, Binary Tree and Binary Search Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 333. Largest BST Subtree?
- LeetCode 333. Largest BST Subtree is rated Medium on LeetCode.
- What topics does LeetCode 333. Largest BST Subtree cover?
- LeetCode 333. Largest BST Subtree is tagged Tree, Depth-First Search, Binary Search Tree, Dynamic Programming and Binary Tree on LeetCode.
- Is LeetCode 333. Largest BST Subtree a premium problem?
- Yes. LeetCode 333. Largest BST Subtree is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.