User Friendly solution (DFS)
Intuition\n Similar question : \nhttps://leetcode.com/problems/maximum-depth-of-binary-tree/description/\n\nThere is a small observation in this problem: when t
# Intuition\n* Similar question : \nhttps://leetcode.com/problems/maximum-depth-of-binary-tree/description/\n\n**There is a small observation in this problem: when the height of the left subtree is equal to the height of the right subtree, it is considered valid. However, there\'s an issue with trees that are at the same level, which is why I first traverse to the bottom. If it\'s not valid, I return -1 directly.**\n\n---\n\n# Approach\n"**The idea is as follows:\nCase 1: If it is a leaf node, directly return 1.\nThen, traverse to the left subtree.\nNext, traverse to the right subtree.\nIf the answer from the left is equal to the answer from the right, what should we return?\nThink about it... (Hint: It\'s related to the maximum depth of a binary tree)."**\nIf not equal then return -1 (means no valid subtree found)\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(1)\n\n# Code\n```cpp []\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode() : val(0), left(nullptr), right(nullptr) {}\n *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\n\nclass Solution {\npublic:\n    vector<int>ans;\n    bool isLeaf(TreeNode* root){\n        return (root->left==NULL && root->right==NULL);\n    }\n    int solve(TreeNode* root){\n        if(root==NULL){\n            return 0;\n        }\n        if(isLeaf(root)){\n            ans.push_back(1);\n            return 1;\n        }\n        int l=solve(root->left);\n        int r=solve(root->right);\n        if(l==r){\n            ans.push_back(1+l+r);\n            return 1+l+r;\n        }\n        return -1;\n    }\n    int kthLargestPerfectSubtree(TreeNode* root, int k) {\n        if(root==NULL){\n            return 0;\n        }   \n        int a= solve(root);\n        for(auto it:ans){\n            cout<<it<<" ";\n        }\n        sort(rbegin(ans),rend(ans));\n        if((k)>ans.size()){\n            return -1;\n        }\n\n        return ans[k-1];\n    }\n};\n```
['C++']