1656. Close Leaf Pairs
A garden is a binary tree of paths: every node is a junction, and a junction without children is a gate. The walking distance between two gates is the number of path segments (edges) on the unique route that joins them.
Given root and an integer d, count the unordered pairs of two different gates whose walking distance is at most d. Return the count as a long. A tree with a single node has one gate and therefore no pairs.
Checking every pair of gates is O(L^2) for L gates and is far too slow. Instead, let each subtree report how many gates sit 0, 1, ..., d-1 segments below its root, and count pairs where their routes first meet. This runs in O(n * d) time and O(n * d) space; avoid deep recursion because the tree can be a long chain.
Example 1
- Input:
- root = [1,2,3,4,5,6,7], d = 3
- Output:
- 2
- Explanation:
Sibling leaves 4,5 and 6,7 are 2 apart; the cross pairs such as 4 and 6 are 4 apart, so with d = 3 only 2 pairs count.
Example 2
- Input:
- root = [1,2,3,null,4], d = 3
- Output:
- 1
- Explanation:
Leaves 4 and 3 are 3 edges apart (4-2-1-3), which is within d = 3, so the answer is 1.
Constraints
1 ≤ number of nodes ≤ 105
1 ≤ d ≤ 10
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n * d)
- Space
- O(n * d)