[Java] DFS
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 */\nclass Solution {\n    List<Integer> ans = new ArrayList<>();\n    \n    public int kthLargestPerfectSubtree(TreeNode root, int k) {\n        dfs(root);\n        \n        Collections.sort(ans);\n        \n        for (int i = ans.size() - 1, j = 1; i >= 0; i--, j++){\n            if (j == k){\n                return ans.get(i);\n            }\n        }\n        \n        return -1;\n    }\n\n    int dfs(TreeNode root){\n        if (root == null){\n            return 0;\n        }\n\n        int left = dfs(root.left);\n        int right = dfs(root.right);\n\n        // either left subtree or right subtree is not perfect subtree\n        if (left == -1 || right == -1){\n            return -1;\n        }\n\n        // left or right children are not equal, it can\'t be perfect subtree\n        if (left != right){\n            return -1;\n        }\n\n        int size = left + right + 1;\n\n        ans.add(size);\n\n        return size;\n    }\n}\n```
['Java']