Practice/LinkedIn/Leetcode 1530. Number of Good Leaf Nodes Pairs
CodingOptional
Given the root of a binary tree and an integer distance, determine how many distinct pairs of leaf nodes exist where the path length between them is at most distance.
A leaf node is defined as a node with no children. The path between two leaf nodes is the shortest route through their lowest common ancestor. Each edge in the tree contributes 1 to the path length.
Your task is to efficiently count these pairs without explicitly checking every possible leaf pair combination.
Example 1:
`
Input: root = [1,2,3,null,4], distance = 3
Output: 1
Explanation:
Tree structure:
1
/
2 3
4
The only leaf nodes are 4 and 3. Path from 4 to 3: 4 → 2 → 1 → 3 (length = 3) Since 3 ≤ 3, this pair counts. Answer: 1 `
Example 2:
`
Input: root = [1,2,3,4,5,6,7], distance = 3
Output: 2
Explanation:
Tree structure:
1
/
2 3
/ \ /
4 5 6 7
Leaf nodes: 4, 5, 6, 7 Valid pairs:
Example 3:
Input: root = [1], distance = 1 Output: 0 Explanation: Only one leaf node exists, so no pairs can be formed.