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.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.
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.
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.
Node.val ≤ 2000rank ≤ 1024root=tree_node([4, 9, 2, 1, 7, 3, 8, None, None, 6, 5]), rank=1
3
Run checks the first 3 tests in your browser. Submit checks all 78 tests on the server, hidden ones included.