Python Simple DFS Solution
Intuition\n Describe your first thoughts on how to solve this problem. \nUse DFS to find perfect subtrees. Store the sizes of the perfect subtrees in an array a
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse DFS to find perfect subtrees. Store the sizes of the perfect subtrees in an array and return the k-th largest size.\n\n# Complexity\n- Time complexity: O(n log n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\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        perfect_sizes = []\n        def dfs(root):\n            nonlocal perfect_sizes\n            if root == None:\n                return 0\n            left = dfs(root.left)\n            right = dfs(root.right)\n            if left == right and left != -1:\n                perfect_sizes.append(left + right + 1)\n                return left + right + 1\n            else:\n                return -1\n\n        dfs(root)\n        perfect_sizes.sort(reverse = True)\n        if k > len(perfect_sizes):\n            return -1\n        return perfect_sizes[k - 1]\n```
['Python3']