#3319
K-th Largest Perfect Subtree Size in Binary Tree
MediumTreeDepth-First SearchSortingBinary TreeDepth-First SearchRecursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
We can use a depth-first search (DFS) to identify perfect binary subtrees while calculating their sizes. This allows us to gather sizes in a single traversal, making it more efficient.
⚙️
Algorithm
3 steps- 1Step 1: Use a DFS approach to traverse the tree and check if each subtree is perfect.
- 2Step 2: For each perfect subtree found, record its size in a list.
- 3Step 3: Sort the list of sizes in non-increasing order and return the k-th largest size.
solution.py23 lines
1class TreeNode:
2 def __init__(self, val=0, left=None, right=None):
3 self.val = val
4 self.left = left
5 self.right = right
6
7class Solution:
8 def kthLargestPerfectSubtreeSize(self, root, k):
9 sizes = []
10 def dfs(node):
11 if not node:
12 return 0
13 left_size = dfs(node.left)
14 right_size = dfs(node.right)
15 if left_size == right_size:
16 size = left_size + right_size + 1
17 sizes.append(size)
18 return size
19 return -1
20
21 dfs(root)
22 sizes.sort(reverse=True)
23 return sizes[k-1] if k <= len(sizes) else -1ℹ
Complexity note: The time complexity is O(n log n) due to sorting the sizes after collecting them, while the DFS traversal itself is O(n). The space complexity is O(n) for storing the sizes.
- 1A perfect binary subtree must have both children as perfect binary subtrees.
- 2Using DFS allows us to efficiently check and collect sizes in one pass.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.