Number of Good Leaf Nodes Pairs

You are given the root of a binary tree and an integer distance. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance.

Return the number of good leaf node pairs in the tree.

Example 1
        1
       / \
      2   3
       \
        4
Inputroot = [1,2,3,null,4], distance = 3
Output1
The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3, so this is the only good pair.
Example 2
        1
       / \
      2   3
     / \ / \
    4  5 6  7
Inputroot = [1,2,3,4,5,6,7], distance = 3
Output2
The good pairs are [4,5] and [6,7] with shortest path = 2, while [4,6] is not good because the length of their shortest path is 4.

Constraints

  • The number of nodes in the tree is in the range [1, 2^10].
  • 1 <= Node.val <= 100
  • 1 <= distance <= 10

Asked at 3 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