Simple solution in Swift using DFS and Heap
Intuition\n Describe your first thoughts on how to solve this problem. \nRecursively traverse using DFS. Compare total nodes in each subtree.\n# Approach\n Desc
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nRecursively traverse using DFS. Compare total nodes in each subtree.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nDFS and Heap. DFS to traverse, heap to keep track of max sum of nodes.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(nlogn)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```swift []\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n *     public var val: Int\n *     public var left: TreeNode?\n *     public var right: TreeNode?\n *     public init() { self.val = 0; self.left = nil; self.right = nil; }\n *     public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }\n *     public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {\n *         self.val = val\n *         self.left = left\n *         self.right = right\n *     }\n * }\n */\n\nimport Collections\n\nclass Solution {\n\n    var heap = Heap<Int>()\n\n    func kthLargestPerfectSubtree(_ root: TreeNode?, _ k: Int) -> Int {\n\n        _ = dfs(root)\n\n        // If k is greater than total PBT found, return -1.\n        if heap.count < k {\n            return -1\n        }\n\n        // Return kth largest sum using heap.\n        var kthSum: Int?\n        for _ in 0..<k {\n            kthSum = heap.popMax()\n        }\n\n        return kthSum ?? -1\n    }\n\n    // Returns total count if the subtree is PBT, else -1.\n    func dfs(_ root: TreeNode?) -> Int {\n        guard let root else { return 0 }\n\n        let left = dfs(root.left)\n        let right = dfs(root.right)\n\n        // If a subtree returns -1, that means it isn\'t perfect binary tree.\n        // If count of subtrees is same, return the total count.\n        // Keep the count in a heap.\n        if left != -1, left == right {\n            let count = left + right + 1\n\n            // Store the count in heap.\n            heap.insert(count)\n            return count\n        } else {\n            return -1\n        }\n    }\n}\n```
['Swift']