Largest Subtree of a Reporting Tree That Is a Valid BST

Last updated: November 29, 2026

Quick Overview

Given a binary tree of employee IDs, return the size of the largest subtree (a node and all its descendants) that is a valid BST.

Meta
Coding & Algorithms
Software Engineer
Meta
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Medium

0

0

0 solved


Given a binary tree of employee IDs, return the size of the largest subtree (a node and all its descendants) that is a valid BST.

Meta onsites use this to test post-order aggregation: each node needs facts from both children before it can decide. The interviewer wants a single O(n) pass that returns (is_bst, size, min, max) rather than re-validating every subtree.

What the Interviewer Expects
  • Reject the O(n^2) validate-every-subtree approach
  • Use post-order traversal returning a tuple
  • Combine child results with min and max bounds
  • Use sentinels so empty children pass automatically
  • State O(n) time
Key Topics to Cover
BST
post-order traversal
tree DP
recursion
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Return the root of that subtree.
  • What if a subtree means any connected set of nodes rather than full descendants?
  • Find the largest BST subtree by sum of values instead of size.
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Input: root of a binary tree with integer values.
  • A subtree must include all descendants of its root.
  • Output: number of nodes in the largest such subtree that is a BST (strict ordering)....
High-Level Design

A subtree rooted at node is a BST exactly when both child subtrees are BSTs and max(left) < node.val < min(right). So each call returns four facts: whether it is a BST, its size, its minimum, its ...


Submit Your Answer
Markdown supported