Largest BST Subtree

Pattern: Largest BST in a binary tree

medium

Post-order: each node reports whether its subtree is a BST, its size, and its smallest and largest values. A node forms a BST when both children do, the left maximum is below it and the right minimum above it. Track the largest size.

The problem

Return the number of nodes in the largest subtree that is a BST (a subtree means a node and all its descendants). The example gives 3. LeetCode's version is premium. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • What must hold for a node's subtree to be a BST?
  • What four facts should each child report?
  • Why is checking each subtree separately slow?

Hints

    Brute force, and why it fails

    Validate every subtree separately: O(n²).

    The key insight

    Reporting min, max and size bottom up decides every subtree in O(1), so one pass is enough.

    Dry run

    best1

    Tree [10, 5, 15, 1, 8, null, 7]. 1, 8 and 7 are BSTs of size 1.

    Step 1 of 3

    The plan

    scan(n): null -> (0, +inf, -inf)
      combine children; if not a BST: mark it
      else size = ls + rs + 1; best = max(best, size); return (size, min, max)
    

    Complexity

    Time
    O(n)
    Space
    O(h)

    One post-order pass.

    Edge cases

    • Empty tree: 0.
    • The whole tree is a BST.
    • Only leaves are BSTs: 1.
    I've built my logic, show the code

    Java

    class Solution {
        private int best;
    
        public int largestBSTSubtree(TreeNode root) {
            best = 0;
            scan(root);
            return best;
        }
    
        private int[] scan(TreeNode n) {            // {size or -1 if not a BST, min, max}
            if (n == null) return new int[]{0, Integer.MAX_VALUE, Integer.MIN_VALUE};
            int[] l = scan(n.left), r = scan(n.right);
            if (l[0] < 0 || r[0] < 0 || l[2] >= n.val || r[1] <= n.val) return new int[]{-1, 0, 0};   // not a BST here
            int size = l[0] + r[0] + 1;
            best = Math.max(best, size);
            return new int[]{size, Math.min(l[1], n.val), Math.max(r[2], n.val)};
        }
    }

    C++

    class Solution {
    public:
        int best;
    
        int largestBSTSubtree(TreeNode* root) {
            best = 0;
            scan(root);
            return best;
        }
    
        vector<int> scan(TreeNode* n) {             // {size or -1 if not a BST, min, max}
            if (n == NULL) return vector<int>{0, INT_MAX, INT_MIN};
            vector<int> l = scan(n->left), r = scan(n->right);
            if (l[0] < 0 || r[0] < 0 || l[2] >= n->val || r[1] <= n->val) return vector<int>{-1, 0, 0};   // not a BST here
            int size = l[0] + r[0] + 1;
            best = max(best, size);
            return vector<int>{size, min(l[1], n->val), max(r[2], n->val)};
        }
    };

    Python

    class Solution:
        def largestBSTSubtree(self, root) -> int:
            best = 0
    
            def scan(n):                            # (size or -1 if not a BST, min, max)
                nonlocal best
                if n is None:
                    return 0, float("inf"), float("-inf")
                ls, lmin, lmax = scan(n.left)
                rs, rmin, rmax = scan(n.right)
                if ls < 0 or rs < 0 or lmax >= n.val or rmin <= n.val:
                    return -1, 0, 0                 # not a BST here
                size = ls + rs + 1
                best = max(best, size)
                return size, min(lmin, n.val), max(rmax, n.val)
    
            scan(root)
            return best

    Common mistakes

    • Using only the children's values instead of their min and max.
    • Counting a subtree whose child is not a BST.

    Similar problems