Java Simple Solution | Weekly Contest
Code\njava []\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n *     int val;\n *     TreeNode left;\n *     TreeNode right;\n *     Tr
# 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 */\n\nclass Pair<T1, T2, T3> {\n        public T1 first;\n        public T2 second;\n        public T3 third;\n    \n        public Pair(T1 first, T2 second, T3 third) {\n            this.first = first;\n            this.second = second;\n            this.third = third;\n        }\n}\n\nclass Solution {\n    List<Integer> list;\n    \n    private Pair<Boolean, Integer, Integer> solveTree(TreeNode root){\n//         Edge\n        if(root==null){\n            return new Pair<Boolean, Integer, Integer>(true, 0,0);\n        }\n        \n//         solve it\n        Pair<Boolean, Integer, Integer> leftsubtree = solveTree(root.left);\n        Pair<Boolean, Integer, Integer> rightsubtree = solveTree(root.right);\n        if(leftsubtree.first && rightsubtree.first && leftsubtree.second==rightsubtree.second){\n            int size = leftsubtree.third+rightsubtree.third+1;\n            list.add(size);\n            \n            int height = leftsubtree.second+1;\n            return new Pair<Boolean, Integer, Integer>(true, height, size);\n        }\n        \n        return new Pair<Boolean, Integer, Integer>(false, 0,0);\n    }\n    \n    public int kthLargestPerfectSubtree(TreeNode root, int k) {\n         list = new ArrayList<>();\n        solveTree(root);\n        \n        Collections.sort(list, Collections.reverseOrder());\n        if(list.size()>=k){\n            return list.get(k-1);\n        }\n        return -1;\n    }\n}\n```
['Math', 'Tree', 'Binary Search Tree', 'Binary Tree', 'Java']