Javascript - DFS + Priority Queue
Code\njavascript []\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n *     this.val = (val===undefined ? 0 : val)\n *    
# Code\n```javascript []\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.left = (left===undefined ? null : left)\n *     this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @param {number} k\n * @return {number}\n */\nvar kthLargestPerfectSubtree = function (root, k) {\n  const minHeap = new MinHeap([]);\n  dfs(root, k, minHeap);\n  return minHeap.getLength() < k ? -1 : minHeap.peek();\n};\n\nfunction dfs(root, k, minHeap) {\n  if (!root) return [true, 0];\n\n  const [isLeftPerfect, leftCount] = dfs(root.left, k, minHeap);\n  const [isRightPerfect, rightCount] = dfs(root.right, k, minHeap);\n  const sum = leftCount + rightCount + 1;\n\n  if (!isLeftPerfect || !isRightPerfect || leftCount !== rightCount) {\n    return [false, sum];\n  }\n\n  if (minHeap.getLength() < k) {\n    minHeap.insert(sum);\n  } else if (sum > minHeap.peek()) {\n    minHeap.remove();\n    minHeap.insert(sum);\n  }\n\n  return [true, sum];\n}\n```\n[MinHeap Link](https://github.com/faustaleonardo/data-structure-in-js/blob/main/MinHeap.js)
['Depth-First Search', 'Heap (Priority Queue)', 'JavaScript']