Number of Good Leaf Nodes Pairs

Medium Topics Company Tags

Return the number of unordered pairs of different leaf nodes whose shortest connecting path contains at most distance edges. A leaf is a node with no children.

A path may go upward through parents and then downward into another subtree. Count each pair once. Node values do not identify nodes: two distinct leaves may have the same value.

Examples use level-order arrays. After the root, each present node contributes left and right child entries in queue order. null marks a missing child, and trailing missing entries may be omitted.

Example 1:

Number of Good Leaf Nodes Pairs, example 1: illustration of the example

Input: root = [8,3,6,1,5,2,7]
distance = 4

Output: 6

Explanation: There are four leaves: 1, 5, 2, and 7. Leaves with the same parent are two edges apart, and leaves in opposite root subtrees are four edges apart. All six unordered pairs qualify.

Example 2:

Number of Good Leaf Nodes Pairs, example 2: illustration of the example

Input: root = [8,3,6,1,5,2,7]
distance = 2

Output: 2

Explanation: Only the two sibling pairs qualify: (1,5) and (2,7), each connected by two edges. Every other leaf pair needs four edges, which exceeds the limit.

Example 3:

Number of Good Leaf Nodes Pairs, example 3: illustration of the example

Input: root = [4,4,4]
distance = 1

Output: 0

Explanation: The two leaves are different nodes even though both have value 4. Their path has two edges, so no pair qualifies when distance is 1.

Constraints:

  • The tree contains between 1 and 1024 nodes.
  • 1 <= Node.val <= 100
  • 1 <= distance <= 10


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.