K-th Largest Perfect Subtree Size in Binary Tree Problem
#3319
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3319.
You are given the root of a binary tree and an integer k.
Return an integer denoting the size of the k^th largest perfect binary subtree, or -1 if it doesn't exist.
A perfect binary tree is a tree where all leaves are on the same level, and every parent has two children.
Example 1:
Input: root = [5,3,6,5,2,5,7,1,8,null,null,6,8], k = 2
Output: 3
Explanation:

The roots of the perfect binary subtrees are highlighted in black. Their sizes, in non-increasing order are [3, 3, 1, 1, 1, 1, 1, 1].
The 2^nd largest size is 3.
Example 2:
Input: root = [1,2,3,4,5,6,7], k = 1
Output: 7
Explanation:

The sizes of the perfect binary subtrees in non-increasing order are [7, 3, 3, 1, 1, 1, 1]. The size of the largest perfect binary subtree is 7.
Example 3:
Input: root = [1,2,3,null,4], k = 3
Output: -1
Explanation:

The sizes of the perfect binary subtrees in non-increasing order are [1, 1]. There are fewer than 3 perfect binary subtrees.
Constraints:
- The number of nodes in the tree is in the range
[1, 2000]. 1 <= Node.val <= 20001 <= k <= 1024
Solution
Approach: DFS + Sorting
Write a recursive function dfs(node) that returns the size of the subtree under node if it is a perfect binary tree, and -1 otherwise, and records every perfect size it finds in a list nums.
- An empty node returns
0. - Compute the results
landrfor the left and right children. - If either is
-1, orl != r, the subtree is not perfect: return-1. - Otherwise the subtree is perfect with size
l + r + 1. Add it tonumsand return it.
After the traversal, if nums has fewer than k entries return -1. Otherwise sort nums in descending order and return the k-th entry.
Complexity: O(n log n) time and O(n) space, where n is the number of nodes.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def kthLargestPerfectSubtree(self, root: Optional[TreeNode], k: int) -> int:
def dfs(root: Optional[TreeNode]) -> int:
if root is None:
return 0
l, r = dfs(root.left), dfs(root.right)
if l < 0 or l != r:
return -1
cnt = l + r + 1
nums.append(cnt)
return cnt
nums = []
dfs(root)
if len(nums) < k:
return -1
nums.sort(reverse=True)
return nums[k - 1]