Number of Good Leaf Nodes Pairs LeetCode solution in Python
1class Solution:2def countPairs(self, root: TreeNode, distance: int) -> int:3adjList = defaultdict(list)4leaves = []5ct = 067def dfs(node, parent):8if node:9if not node.left and not node.right:10leaves.append(node)11adjList[node].append(parent)12adjList[parent].append(node)13dfs(node.left, node)14dfs(node.right, node)1516dfs(root, None)1718# bfs from each leaf till we find another leaf19for leaf in leaves:20q = deque([(leaf, 0)])21seen = set()22while q:23curr, dist = q.popleft()24seen.add(curr)25if dist > distance:26break27for nbr in adjList[curr]:28if nbr and nbr not in seen:29if nbr in leaves and dist + 1 <= distance:30ct += 131q.append((nbr, dist + 1))3233return ct // 2