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: 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
K-th Largest Perfect Subtree Size INPUT Binary Tree Structure 5 3 6 5 2 5 7 1 8 root = [5,3,6,5,2,5,7,1, null,null,null,null,null,null,8] k = 2 Perfect Subtrees Found: [7, 3, 3, 1, 1, 1, 1] ALGORITHM STEPS 1 DFS Traversal Visit each node bottom-up 2 Check Perfect Condition Both children same height 3 Calculate Subtree Size Size = 2^(h+1) - 1 4 Sort and Find K-th Sort sizes descending Size Collection Process: Collected: 7 3 3 1 1 Sorted: 7 3 3 1 1 k=2 2nd largest = 3 FINAL RESULT K-th Largest Perfect Subtree Perfect Subtree (size=3) 3 5 2 Output: 3 OK - Valid Result The 2nd largest perfect subtree has 3 nodes Key Insight: A perfect binary tree has size 2^(height+1) - 1. Use DFS post-order traversal to check if both subtrees are perfect with equal heights. Collect all perfect subtree sizes, sort descending, and return the k-th element. Time: O(n log n), Space: O(n) for storing sizes. TutorialsPoint - K-th Largest Perfect Subtree Size in Binary Tree | DFS Approach
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