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.
Constraints
-
The number of nodes in the tree is in the range
[1, 2000] -
1 ≤ Node.val ≤ 2000 -
1 ≤ k ≤ 1024
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.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code