K-th Largest Perfect Subtree Size in Binary Tree - Problem
K-th Largest Perfect Subtree Size in Binary Tree
You're given the
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
Example: In a tree with perfect subtrees of sizes [7, 3, 3, 1, 1], the 2nd largest would be size 3.
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
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
โก Linearithmic
Space Complexity
O(n)
O(h) for recursion stack where h is tree height, plus O(p) for storing perfect subtree sizes
โก Linearithmic Space
Constraints
-
The number of nodes in the tree is in the range
[1, 2000] -
1 โค Node.val โค 2000 -
1 โค k โค 1024
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code