Simple Backward DFS
Complexity
Time complexity:
O(n log n)
Space complexity:
O(n)Code

# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(n log n)
---
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(n)
---
# Code
```cpp []
class Solution {
public:
class Solution {
public:
vector<int>values;
    int maxDepth(TreeNode* root) {
        if(!root) return 0;
       int l =  maxDepth(root->left);
       int r =  maxDepth(root->right);
       int ans = l+r+1;
       if(l==-1 || r==-1 || l!=r) return ans = -1;  
       values.push_back(ans);
        return ans;    
    }
    int kthLargestPerfectSubtree(TreeNode* root, int k) {
        maxDepth(root);
        sort(values.rbegin(), values.rend());
        return (values.size()<k) ? -1: values[k-1];
    }
};
```
```java []
class Solution {
    List<Integer>values = new ArrayList<>();
    int dfs(TreeNode root){
        if(root == null) return 0;
        int lft = dfs(root.left);
        int rgt = dfs(root.right);
        int ans =(lft*2)+1;
        if(lft==-1 || rgt==-1 || lft!=rgt) return ans = -1;
        values.add(ans);
        return ans;
    }
    public int kthLargestPerfectSubtree(TreeNode root, int k) {
        dfs(root);
        Collections.sort(values);
        return (values.size()<k) ? -1 : values.get(values.size()-k);
    }
}
```
['Tree', 'Depth-First Search', 'Sorting', 'Binary Tree', 'C++', 'Java']