Python Medium
python3 []\n# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#       
```python3 []\n# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution:\n    def kthLargestPerfectSubtree(self, root: Optional[TreeNode], k: int) -> int:\n        \'\'\'\n        N^2 works\n        \n        node.val doesnt matter\n        \n        brute force all possible perfect binary tree sizes\n        \n        sort the results\n        \n        return self.A[k - 1] if len(self.A) >= k else -1\n         \n        \n        bfs for each node\n        \'\'\'\n        \n        self.A = []\n        \n        def bfs(node):\n            q = deque()\n            q.append(node)\n            level = 0\n            \n            while q:\n                nxt = deque()\n                \n                while q:\n                    node = q.popleft()\n                    if node.left:\n                        nxt.append(node.left)\n                    if node.right:\n                        nxt.append(node.right)\n                \n                \n                \n                if not nxt:\n                    self.A.append((1 << (level + 1)) - 1)\n                    return\n                \n                if len(nxt) != (1 << (level + 1)):\n                    return\n                \n                level += 1\n                q = nxt\n                \n            \n        \n        \n        \n        \n        \n        def dfs(node):\n            if not node:\n                return \n            \n            bfs(node)\n            dfs(node.left)\n            dfs(node.right)\n            \n            \n            \n            \n        dfs(root)\n        \n        \n        self.A.sort(reverse=True)\n        if len(self.A) < k:\n            return -1\n        return self.A[k - 1]\n        \n```
['Python3']