Python O(n + k*log(n)) Efficient Solution
Intuition
do Bottom-up DFS to check if children are perfect subtrees.
Complexity
Time complexity: O(n + k*log(n))

Space complexity: O(n)
Code
# Intuition 
* do Bottom-up DFS to check if children are perfect subtrees.
<!-- Describe your first thoughts on how to solve this problem. -->


# Complexity
- Time complexity: O(n + k*log(n))
<!-- Add your time complexity here, e.g. $$O(n)$$ -->

- Space complexity: O(n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

# Code
```python3 []
# 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
import heapq
class Solution:
    def kthLargestPerfectSubtree(self, root: Optional[TreeNode], k: int) -> int:
        heap = []


        def dfs(root):
            if not root:
                return 0

            # Implement base case here, a single node counts as a perfect tree.
            if not root.left and not root.right:
                heapq.heappush(heap, -1)
                return 1

            # Recursively search through the children.
            left = dfs(root.left)
            right = dfs(root.right)

            # Case for any other node in the tree, if we have two valid perfect subtrees
            # parent also becomes part of the perfect subtree, so we add +1 to the left and right.
            if left and right and left == right:
                heapq.heappush(heap, -(1 + left + right))
                return 1 + left + right

            # Otherwise, we do not have a perfect subtree, just return 0
            return 0


        dfs(root)

        # Use a heap, more efficient than sorting for most cases (n*log(k))
        while heap and  k-1:
            heapq.heappop(heap)
            k -=1
        
        return -heapq.heappop(heap) if heap else -1
```
['Python3']