K-th Largest Perfect Subtree Size in Binary Tree

You are given the root of a binary tree and an integer k.

Return an integer denoting the size of the k^th largest perfect binary subtree, or -1 if it doesn't exist.

A perfect binary tree is a tree where all leaves are on the same level, and every parent has two children.

Example 1
            5
          /   \
         3     6
        / \   / \
       5   2 5   7
      / \   / \
     1   8 6   8
Inputroot = [5,3,6,5,2,5,7,1,8,null,null,6,8], k = 2
Output3
The perfect binary subtree sizes in non-increasing order are [3, 3, 1, 1, 1, 1, 1, 1], so the 2^nd largest size is 3.
Example 2
        1
       / \
      2   3
     / \ / \
    4  5 6  7
Inputroot = [1,2,3,4,5,6,7], k = 1
Output7
The perfect binary subtree sizes in non-increasing order are [7, 3, 3, 1, 1, 1, 1], so the largest size is 7.

Constraints

  • The number of nodes in the tree is in the range [1, 2000].
  • 1 <= Node.val <= 2000
  • 1 <= k <= 1024

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate