My first instinct was to just do a DFS and check each subtree independently, which would have been O(n^2) and I knew that was wrong but I said it out loud anyway.
Use a post-order DFS to compute the height and node count of each subtree, and determine if it is perfect by checking that both children are perfect and have equal heights. Collect the sizes of all perfect subtrees, sort them in descending order, and return the k-th largest or -1 if there are fewer than k.
Pro tip: During the DFS, you can maintain a min-heap of size k to track the k largest sizes, avoiding a full sort and achieving O(n log k) time. Also, clarify with the interviewer whether k is 1-indexed and whether the tree can be empty.
Confirm the definition of a perfect binary tree and the meaning of k-th largest (e.g., 1-indexed). Discuss edge cases like empty tree, k <= 0, or fewer than k perfect subtrees.
Decide that each DFS call returns a tuple: (isPerfect, height, size). For a null node, return (true, -1, 0) or similar. For a leaf, return (true, 0, 1).
Recursively process left and right children. A subtree is perfect if both children are perfect and their heights are equal. Compute height = left.height + 1 and size = left.size + right.size + 1.
If the subtree is perfect, add its size to a min-heap of size k (or a list). If using a heap, push the size and if heap size exceeds k, pop the smallest. This keeps the k largest sizes.
After traversal, if the heap has fewer than k elements, return -1. Otherwise, the root of the min-heap is the k-th largest size. If using a list, sort descending and return the (k-1)-th element.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.