DFS for Perfect Subtrees.
ApproachThe function kthLargestPerfectSubtree finds the k-th largest "perfect" subtree in a binary tree. A perfect subtree is one where all levels are completel
# Approach
The function `kthLargestPerfectSubtree` finds the k-th largest "perfect" subtree in a binary tree. A perfect subtree is one where all levels are completely filled, and both the left and right subtrees are perfect and have the same height. The function uses a depth-first search (DFS) to check each subtree, adding the height of any perfect subtree to a list. After collecting all the heights, the list is sorted, and the k-th largest height is picked. The size of that subtree is then calculated as `(2^height - 1)` since that’s the formula for a perfect subtree's size. If there aren’t enough perfect subtrees or the tree is empty, it returns `-1`. It’s a straightforward way to find and rank perfect subtrees in the tree.

# Complexity
- Time complexity:
O(n + mlogm).

- Space complexity:
O(m + h).

# Code
```cpp []
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
public:
    int kthLargestPerfectSubtree(TreeNode* root, int k) {
        vector<int> treeSize;
        int ht = dfs(root, treeSize);
        if (k <= treeSize.size()) {
            sort(treeSize.begin(),treeSize.end());
            int n = treeSize.size();
            int val = treeSize[n - k];
            return (1 << val) - 1;
        }
        return -1;
    }
    int dfs(TreeNode* root, vector<int>& treeSize) {
        if (!root)
            return 0;
        int lh = dfs(root->left, treeSize);
        int rh = dfs(root->right, treeSize);
        if (lh >= 0 && lh == rh) {
            treeSize.push_back(lh + 1);
            return (lh + 1);
        }
        return -1;
    }
};
```
['C++']