Problem Description
Given a binary tree and an integer distance, count the number of pairs of leaf nodes such that the shortest path between them is less than or equal to distance. A pair is only considered if both nodes are leaves and they are distinct.
Key Insights
- Use a depth-first search (DFS) to traverse the tree.
- At each node, gather the distances of leaf nodes from that node.
- For a non-leaf node, combine the results from the left and right children to count valid leaf pairs.
- Increment the distance values as you return to parent nodes and discard distances greater than the allowed distance.
- The efficiency relies on the fact that the maximum distance is small, allowing a simple pairwise combination at each node.
Space and Time Complexity
Time Complexity: O(n * d^2), where n is the number of nodes and d is the given maximum distance. Space Complexity: O(n), for recursive call stack and storing distance lists.
Solution
We use DFS to traverse the tree. For each node:
- If it is a leaf, return a list containing a single element 1 (distance from itself to its parent).
- If it is an internal node, recursively obtain distance lists from both the left and right children.
- For every combination of a distance from the left child and a distance from the right child, check if the sum is less than or equal to the provided distance. If yes, increment the global count.
- Prepare a new list of distances for the current node by incrementing all distances from the children by 1, filtering out those that exceed the maximum allowed distance. By aggregating the counts during the DFS, we count all valid pairs of leaf nodes.
Code Solutions
Below are code implementations in multiple languages.