Problem Description
Given the root of a binary tree and an integer k, find the size of the kth largest perfect binary subtree. A perfect binary subtree is one in which all leaves are on the same level and every internal node has exactly two children. If there are fewer than k perfect subtrees in the tree, return -1.
Key Insights
- Traverse the tree using DFS (postorder traversal) so that subtrees are processed before their parent.
- For each node, determine if it forms the root of a perfect binary subtree:
- A leaf node is a perfect binary subtree of height 1 and size 1.
- For an internal node, if both left and right subtrees are perfect and have the same height, then the subtree rooted at the current node is perfect.
- Record the size of every perfect subtree encountered (including those that are parts of a larger perfect subtree).
- After traversal, sort the collected perfect subtree sizes in descending order. The kth element in this list is the answer.
- Be cautious in handling null children; use base-case values appropriately.
Space and Time Complexity
Time Complexity: O(n log n) in the worst-case due to sorting all perfect subtree sizes (n being the number of nodes). The DFS itself is O(n).
Space Complexity: O(n) for the recursion stack and to store the sizes of perfect subtrees.
Solution
We use a DFS (depth-first search) to traverse every node in the binary tree. At each node:
- If the node is a leaf, then it is by definition a perfect binary subtree with height 1 and size 1.
- Otherwise, recuse on both children. If both left and right subtrees are perfect and have the same height, then the current node’s subtree is also perfect. Its height is one plus the children’s height, and its size is the sum of the children’s sizes plus one.
- Record the size of any perfect subtree found. After the DFS traversal, sort the list of perfect subtree sizes in descending order and return the kth element if it exists, otherwise return -1.
Data structures used:
- A list to collect perfect subtree sizes.
- Recursion with additional tuple values (isPerfect, height, size) to keep track of subtree properties.