100% runtime ✅ and memory ✅ beats Java solution
\n\n# Intuition\nTo find the size of the kth largest perfect binary subtree, we need to identify all subtrees that are perfect binary trees and count their size
![image.png](https://assets.leetcode.com/users/images/018125ea-8004-4f28-a7e4-6b79ffa99861_1728792238.8237424.png)\n\n# Intuition\nTo find the size of the kth largest perfect binary subtree, we need to identify all subtrees that are perfect binary trees and count their sizes. A perfect binary tree has equal height subtrees on both sides.\n\n# Approach\n1. Traverse the binary tree using a recursive function that checks if the left and right subtrees are perfect and have equal height.\n2. Store the height of each perfect subtree in a list.\n3. Sort the heights in descending order.\n4. Compute the size using the kth largest perfect subtree height if it exists, or -1 if it doesn\'t exist.\n\n# Complexity\n- Time complexity:\n\uD835\uDC42(\uD835\uDC5Blog\u2061\uD835\uDC5B) due to sorting the heights of subtrees.\n\n- Space complexity:\n\uD835\uDC42(\uD835\uDC5B) to store the subtree heights.\n\n# Code\n```java []\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     TreeNode() {}\n *     TreeNode(int val) { this.val = val; }\n *     TreeNode(int val, TreeNode left, TreeNode right) {\n *         this.val = val;\n *         this.left = left;\n *         this.right = right;\n *     }\n * }\n */\nclass Solution {\n    private int isPerfect(TreeNode root,ArrayList<Integer> al){\n        if(root==null){\n            return 0;\n        }\n        int l = this.isPerfect(root.left,al), r = this.isPerfect(root.right,al);\n        if(l>=0 && r>=0 && l == r){\n            al.add(l+1);\n            return l+1;\n        }\n        return -1;\n    }\n    public int kthLargestPerfectSubtree(TreeNode root, int k) {\n        ArrayList<Integer> al = new ArrayList<>();\n        this.isPerfect(root,al);\n        Collections.sort(al,Collections.reverseOrder());\n        /*for(int i:al){\n            System.out.println(i);\n        }*/\n        if(al.size()<k){\n            return -1;\n        }\n        int p = al.get(k-1);\n        return (1<<p)-1;\n    }\n}\n```\n\n\n# Upvote if you find it helpful
['Recursion', 'Binary Tree', 'Java']