Python 1530.py
class Solution:
def countPairs(self, root: TreeNode, distance: int) -> int:
id = 0 # unique ID during traversal
leafs = [] # check only leaf nodes
# add node.parent to each child and a unique ID
def findParent(node, parent):
if node:
nonlocal id
# inject parent
node.parent = parent
node.id = id
id += 1
if node.left or node.right:
# going deeper
findParent(node.left, node)
findParent(node.right, node)
else:
# store leaf node
leafs.append(node)
# identify all leaf nodes and track their parent
findParent(root, None)
# find common parent of two nodes (helper for count())
def ancestor(left, right):
visited = set()
scan = left
while scan:
visited.add(scan.id)
scan = scan.parent
scan = right
while scan:
if scan.id in visited:
# found shared parent
return scan
scan = scan.parent
# length(left, parent) + length(right, parent)
def count(left, right):
edges = 0
parent = ancestor(left, right)
scan = left
while scan != parent:
scan = scan.parent
edges += 1
scan = right
while scan != parent:
scan = scan.parent
edges += 1
return edges
result = 0
for i in range(len(leafs)):
for j in range(i + 1, len(leafs)):
if count(leafs[i], leafs[j]) <= distance:
result += 1
return result
Difficulty
and has an acceptance rate of about 72% (200k+ submissions).
Typical patterns to solve this problem:
- Binary Tree
- Depth First Search
- Tree
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a method that counts the number of leaf-node pairs in a binary tree whose shortest path length does not exceed a given distance. It augments each node with a reference to its parent and a unique identifier, gathers all leaf nodes, and then evaluates every unordered leaf pair using helper functions that locate a common ancestor and compute the edge count between the two leaves.
Traversal and Leaf Collection
A depth-first traversal is performed by the nested findParent function. For each visited node the function stores a reference to its parent in a new attribute parent and assigns a sequential integer to a new attribute id. When a node has no left or right child it is recognized as a leaf and appended to the leafs list.
def findParent(node, parent):
if node:
nonlocal id
node.parent = parent
node.id = id
id += 1
if node.left or node.right:
findParent(node.left, node)
findParent(node.right, node)
else:
leafs.append(node)
This step ensures that later calculations can move upward from any leaf without recomputing the path from the root.
Ancestor Determination
The ancestor helper locates the lowest common ancestor of two leaf nodes. It walks upward from the first leaf, recording each visited node’s identifier in a set. Then it walks upward from the second leaf until it encounters an identifier already present in the set, at which point that node is the shared ancestor.
def ancestor(left, right):
visited = set()
scan = left
while scan:
visited.add(scan.id)
scan = scan.parent
scan = right
while scan:
if scan.id in visited:
return scan
scan = scan.parent
Using a set provides constant-time membership checks, allowing the common ancestor to be found in time proportional to the depth of the deeper leaf.
Distance Computation
Once the common ancestor is known, the count function measures the number of edges on the path between the two leaves. It walks from each leaf up to the ancestor, incrementing a counter for each step.
def count(left, right):
edges = 0
parent = ancestor(left, right)
scan = left
while scan != parent:
scan = scan.parent
edges += 1
scan = right
while scan != parent:
scan = scan.parent
edges += 1
return edges
The sum of the two upward traversals yields the total edge count between the leaves.
Pair Evaluation
The main body of the method iterates over all unordered pairs of leaf nodes stored in leafs. For each pair it invokes count and increments the result counter when the distance does not exceed the supplied limit.
result = 0
for i in range(len(leafs)):
for j in range(i + 1, len(leafs)):
if count(leafs[i], leafs[j]) <= distance:
result += 1
return result
Because the outer loop runs from the first leaf to the last and the inner loop starts one position ahead, each distinct pair is examined exactly once.
Edge Cases Handled
The algorithm gracefully handles an empty tree: the initial call to findParent receives None, leaving leafs empty and causing the final loops to execute zero iterations, resulting in a return value of zero. A tree consisting of a single leaf also yields zero pairs, as the double loop never finds a second leaf to pair with. When the distance argument is zero, the condition count(...) <= distance can never be satisfied for distinct leaves, again producing a zero result. Conversely, a very large distance value permits all possible leaf pairs to be counted, as the distance check will always succeed.
Performance Considerations
The design introduces parent pointers and unique identifiers during a single traversal, which eliminates the need to recompute paths from the root for each leaf pair. The use of a set in the ancestor search provides fast detection of a shared node, avoiding repeated linear scans of ancestor chains. By storing leaf nodes in a list, the algorithm restricts pairwise distance calculations to the relevant subset of nodes, bypassing internal nodes that could never form a valid pair. These choices collectively reduce overhead compared to a naïve approach that might repeatedly traverse from the root for every pair.
ELI5 - Simplified Explanation
Imagine this structure is a giant tree growing upside down in the sky. At the very tips of the branches are little things called leaf nodes. The goal is to see how many pairs of these leaves are close enough to each other based on a specific distance.
First, the code travels through the entire tree starting from the top. As it explores, it remembers how every piece connects to the one above it, like a map showing parent branches. It keeps track of every single leaf it finds and remembers its own specific spot.
Once all the leaves are gathered, the code compares them in pairs. To figure out the distance between any two leaves, it looks for the exact spot where their paths connect. It traces the path from one leaf up to that connecting point and then back down to the second leaf. By counting how many little steps it takes to make that trip, it knows the distance between them.
If that count is small enough, the pair is a match. The code repeats this process for every possible pair of leaves to see how many of them are close enough to be friends.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | |||||||
| leetcode.ca | C++ | Java | Python | JS | Go | TS | |||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fartem | Ruby | ||||||||
| FelixFan1122 | Java | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| MacJim | C++ | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Java | ||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fartem | Ruby | ||||||||
| FelixFan1122 | Java | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| MacJim | C++ | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 892: Surface Area of 3D Shapes
- problem 1266: Minimum Time Visiting All Points
- problem 2481: Minimum Cuts to Divide a Circle
- problem 1405: Longest Happy String
- problem 1250: Check If It Is a Good Array
- problem 1610: Maximum Number of Visible Points
- problem 2444: Count Subarrays With Fixed Bounds
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality