Soln 2: class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def __init__(self): self.perfect_subtree_sizes = [] def isPerfect(self, root): # Base case: if the node is null, it's a perfect subtree of size 0 if not root: return True, 0 # Check left and right subtrees recursively left_perfect, left_size = self.isPerfect(root.left) right_perfect, right_size = self.isPerfect(root.right) # If both subtrees are perfect and have the same size, the current subtree is perfect if left_perfect and right_perfect and left_size == right_size: size = 1 + left_size + right_size # Add 1 for the root self.perfect_subtree_sizes.append(size) return True, size # If not perfect, return False and size 0 return False, 0 def kthLargestPerfectSubtree(self, root, k: int) -> int: # First pass to fill up the list of perfect subtree sizes self.isPerfect(root) # Sort sizes in descending order self.perfect_subtree_sizes.sort(reverse=True) # If there are at least k perfect subtrees, return the k-th largest, otherwise return -1 if len(self.perfect_subtree_sizes) >= k: return self.perfect_subtree_sizes[k - 1] return -1