Ctrl K

Perfect Subtrees by Size

Medium
You are given the root of a binary tree and an integer rank. Call a subtree **perfect** if every internal node in it has exactly two children and all of its leaves sit at the same depth. The subtree of a node is that node together with all its descendants; a single leaf counts as a perfect subtree of one node. List the sizes (node counts) of all perfect subtrees, one for every node that roots a perfect subtree, and sort them in descending order. Return the rank-th entry of that list (1-based), or -1 if the list is shorter than that.
Example 1
root=tree_node([4, 9, 2, 1, 7, 3, 8, None, None, 6, 5]), rank=1 → 3

The whole tree is not perfect: node 1 has no children while node 7 does. The largest perfect subtrees are rooted at 7 and at 2, with 3 nodes each.

Example 2
root=tree_node([10, 20, 30, 40, 50, 60, 70]), rank=2 → 3

Perfect subtree sizes in descending order: 7, 3, 3, 1, 1, 1, 1. The second one is 3.

Example 3
root=tree_node([5, None, 6]), rank=2 → -1

There is only one perfect subtree here, the leaf 6, so there is no second one.

Constraints
  • 1 ≤ number of nodes ≤ 2000
  • 1 ≤ Node.val ≤ 2000
  • 1 ≤ rank ≤ 1024
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTree Columns, Top Down MediumMerge Two Search Trees MediumTree Columns With Ties HardIs It a Search Tree? MediumTwo Mixed-Up Nodes Medium
loading Python…
Input
root=tree_node([4, 9, 2, 1, 7, 3, 8, None, None, 6, 5]), rank=1
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 78 tests on the server, hidden ones included.