K-th Largest Perfect Subtree Size in Binary Tree - Problem
K-th Largest Perfect Subtree Size in Binary Tree

You're given the root of a binary tree and an integer k. Your task is to find the size of the k-th largest perfect binary subtree within this tree.

A perfect binary tree is a special type of tree where:
โ€ข All leaf nodes are at the same level
โ€ข Every internal node has exactly two children

Return the size (number of nodes) of the k-th largest perfect subtree, or -1 if fewer than k perfect subtrees exist.

Example: In a tree with perfect subtrees of sizes [7, 3, 3, 1, 1], the 2nd largest would be size 3.

Input & Output

example_1.py โ€” Basic Perfect Subtrees
$ Input: root = [5,3,6,5,2,5,7,1,null,null,null,null,null,null,8], k = 2
โ€บ Output: 3
๐Ÿ’ก Note: The perfect subtrees have sizes [1,1,1,1,1,1,3,1]. The 2nd largest size is 3.
example_2.py โ€” Single Node Tree
$ Input: root = [1], k = 1
โ€บ Output: 1
๐Ÿ’ก Note: The only perfect subtree is the root itself with size 1.
example_3.py โ€” No Perfect Subtrees of Required Rank
$ Input: root = [1,2,null,3], k = 2
โ€บ Output: -1
๐Ÿ’ก Note: Only one perfect subtree exists (leaf node 3 with size 1), but we need the 2nd largest.

Visualization

Tap to expand
ASize: 7BSize: 3CSize: 3DEFG๐ŸŽฏ Perfect Subtree Analysis:โ€ข Leaves D,E,F,G: Each size 1 (perfect by definition)โ€ข Nodes B,C: Size 3 each (both children at same height)โ€ข Root A: Size 7 (perfect subtrees B,C have equal height 2)
Understanding the Visualization
1
Identify Leaf Families
Single individuals (leaf nodes) are considered perfect families of size 1
2
Check Parent Generations
A parent forms a perfect family if both children lead perfect families of the same depth
3
Calculate Family Sizes
Perfect family size = left family + right family + parent (1)
4
Collect and Rank
Gather all perfect family sizes and rank them to find the k-th largest
Key Takeaway
๐ŸŽฏ Key Insight: A subtree is perfect if both its children are perfect subtrees of equal height, enabling efficient bottom-up detection in a single traversal.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n log n)

O(n) for single DFS traversal + O(p log p) for sorting perfect subtree sizes where p โ‰ค n

n
2n
โšก Linearithmic
Space Complexity
O(n)

O(h) for recursion stack where h is tree height, plus O(p) for storing perfect subtree sizes

n
2n
โšก Linearithmic Space

Constraints

  • The number of nodes in the tree is in the range [1, 2000]
  • 1 โ‰ค Node.val โ‰ค 2000
  • 1 โ‰ค k โ‰ค 1024
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
43.8K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen