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:
1
💡 Note:
The perfect subtrees have sizes [3,1,1,1,1,1]. After sorting in descending order, the 2nd largest size is 1.
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code