[Java/C++/Python] DFS
Intuition\nIf the left and right child tree are perfect trees\nof the same height,\nthen the root tree is a perfect tree with height + 1\n\n\n\n# Explanation\nD
# **Intuition**\nIf the left and right child tree are perfect trees\n**of the same height**,\nthen the root tree is a perfect tree with `height + 1`\n\n<br>\n\n# **Explanation**\nDFS\nReturn the height of perfect tree.\nReturn -1 if it\'s not perfect tree.\n<br>\n\n# **Complexity**\nItearation part:\nTime `O(n)` for `dfs`\nSpace `O(n)`\n\n`k`th part\n`O(nlogn)` for quick sort\n`O(n)` for quick select and counting sort.\n<br>\n\n**Java**\n```java\n    public int kthLargestPerfectSubtree(TreeNode root, int k) {\n        List<Integer> res = new ArrayList<>();\n        dfs(root, res);\n        Collections.sort(res);\n        if (k <= res.size()) {\n            return (1 << res.get(res.size() - k)) - 1;\n        }\n        return -1;\n    }\n\n    private int dfs(TreeNode root, List<Integer> res) {\n        if (root == null) return 0;\n        int l = dfs(root.left, res), r = dfs(root.right, res);\n        if (l == r && l >= 0) {\n            res.add(l + 1);\n            return l + 1;\n        }\n        return -1;\n    }\n```\n\n**C++**\n```cpp\n    int kthLargestPerfectSubtree(TreeNode* root, int k) {\n        vector<int> res;\n\n        function<int(TreeNode*)> dfs = [&](TreeNode* root) -> int {\n            if (!root) return 0;\n            int l = dfs(root->left), r = dfs(root->right);\n            if (l == r && l >= 0) {\n                res.push_back(l + 1);\n                return l + 1;\n            }\n            return -1;\n        };\n\n        dfs(root);\n        nth_element(res.begin(), res.end() - k, res.end());\n        if (k <= res.size()) {\n            return (1 << res[res.size() - k]) - 1;\n        }\n        return -1;\n    }\n```\n\n**Python**\n```py\n    def kthLargestPerfectSubtree(self, root: Optional[TreeNode], k: int) -> int:\n        res = []\n        def dfs(root):\n            if not root: return 0\n            l, r = dfs(root.left), dfs(root.right)\n            if l == r >= 0:\n                res.append(l + 1)\n                return l + 1\n            return -1\n        dfs(root)\n        return (1 << sorted(res)[-k]) - 1 if k <= len(res) else -1\n```\n
['C', 'Python', 'Java']