#1530
Number of Good Leaf Nodes Pairs
MediumTreeDepth-First SearchBinary TreeDepth-First SearchDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses Depth-First Search (DFS) to count pairs of leaf nodes efficiently. Instead of calculating distances between all pairs, we keep track of the number of leaf nodes at each distance from the current node, allowing us to count good pairs on-the-fly.
⚙️
Algorithm
3 steps- 1Step 1: Perform a DFS traversal of the tree, keeping track of the number of leaf nodes at each distance from the current node.
- 2Step 2: When reaching a leaf node, return an array that counts how many leaf nodes exist at each distance from this node.
- 3Step 3: For each pair of leaf nodes found at the current node, check if their combined distance is within the limit and count them.
solution.py27 lines
1# Full working Python code
2class TreeNode:
3 def __init__(self, val=0, left=None, right=None):
4 self.val = val
5 self.left = left
6 self.right = right
7
8class Solution:
9 def countPairs(self, root: TreeNode, distance: int) -> int:
10 self.count = 0
11 self.dfs(root, distance)
12 return self.count
13
14 def dfs(self, node, distance):
15 if not node:
16 return [0] * (distance + 1)
17 if not node.left and not node.right:
18 return [1] + [0] * distance
19 left_counts = self.dfs(node.left, distance)
20 right_counts = self.dfs(node.right, distance)
21 for i in range(distance):
22 self.count += left_counts[i] * right_counts[distance - 2 - i]
23 counts = [0] * (distance + 1)
24 for i in range(distance):
25 counts[i + 1] = left_counts[i] + right_counts[i]
26 return counts
27ℹ
Complexity note: The complexity is O(n) because we traverse each node once, and the space complexity is O(n) due to the recursion stack and the array used to count distances.
- 1Leaf nodes are the only nodes we care about for counting pairs.
- 2Using DFS allows us to efficiently calculate distances without redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.