Beats 100% 2ms Java Solution.
Code


# Code
```java []
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int kthLargestPerfectSubtree(TreeNode root, int k) {
        int[] cnt = new int[12]; //depth of 11 perf is size = 2^11 - 1 = 2047, large enough to fit constraint.
        dfs(root, cnt);
        int largerCnt = 0; //counts perf trees with depth >= curr depth
        for(int depth = 11; depth > 0; depth--) {
            largerCnt += cnt[depth];
            if(largerCnt >= k) return (1 << (depth)) - 1;
        }
        return -1; //not enough perf trees

    }

    private int dfs(TreeNode root, int[] cnt) { //returns depth of tree if perfect, -1 if imperfect
        if(root == null) return 0;
        int l = dfs(root.left, cnt), r = dfs(root.right, cnt);
        int val = l >= 0 && l == r ? 1 + l : -1;
        if(val != -1) cnt[val]++;
        return val;
    }
}
```
['Java']