K-th Largest Perfect Subtree in a Binary Tree Simplified
IntuitionWe are asked to find the k-th largest perfect subtree in a binary tree. A perfect subtree is one where all internal nodes have two children and all lea
# Intuition
We are asked to find the k-th largest perfect subtree in a binary tree. A perfect subtree is one where all internal nodes have two children and all leaves are at the same depth. To solve this, we need a way to detect perfect subtrees and track their sizes. The idea is to use a bottom-up (post-order) approach to validate and compute each perfect subtree.

# Approach
We perform a post-order traversal using a recursive helper function. For each node, we get results from the left and right children. If both children are perfect and have equal heights, then the current subtree is also perfect. We calculate its size as leftSize + rightSize + 1 and store it in a min-heap (priority queue). We keep the heap size limited to k to ensure that the top of the heap gives the k-th largest perfect subtree size. If fewer than k perfect subtrees exist, we return -1.
# Complexity
- Time complexity:
O(n log k), because we visit every node and perform heap operations of log k time.
- Space complexity:
O(h + k), where h is the height of the tree for the recursion stack and k for the heap.

# 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 {
    priority_queue<int,vector<int>, greater<int>> pq;
    int rank;
    pair<int,int> helper(TreeNode* root){
        if(root == NULL){
            return {0,0};
        }
        pair<int,int> left = helper(root->left);
        pair<int,int> right = helper(root->right);
        pair<int,int> result = {-1,-1};
        if(left.second == right.second and left.second != -1){
            pq.push(left.first+right.first + 1);
            if(pq.size() > this->rank){
                pq.pop();
            }
            result = {left.first+right.first + 1, right.second+1};
        }
        
        return result;
        
    }
public:
    int kthLargestPerfectSubtree(TreeNode* root, int k) {
        this->rank = k;
        helper(root);
        return pq.size() < k?-1:pq.top();
    }
};
```
['C++']