Approach
Depth-first search
For Number of Good Leaf Nodes Pairs, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 76 lines of Python from the credited upstream file number-of-good-leaf-nodes-pairs.py.
- The implementation visibly relies on hash lookup.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4import collections5 6 78class TreeNode(object):9 def __init__(self, val=0, left=None, right=None):10 self.val = val11 self.left = left12 self.right = right13 14 15class Solution(object):16 def countPairs(self, root, distance):17 """18 :type root: TreeNode19 :type distance: int20 :rtype: int21 """22 def iter_dfs(distance, root):23 result = 024 stk = [(1, (root, [collections.Counter()]))]25 while stk:26 step, params = stk.pop()27 if step == 1:28 node, ret = params29 if not node:30 continue31 if not node.left and not node.right:32 ret[0][0] = 133 continue34 left, right = [collections.Counter()], [collections.Counter()]35 stk.append((2, (left, right, ret)))36 stk.append((1, (node.right, right)))37 stk.append((1, (node.left, left)))38 else:39 left, right, ret = params40 for left_d, left_c in left[0].iteritems():41 for right_d,right_c in right[0].iteritems():42 if left_d+right_d+2 <= distance:43 result += left_c*right_c44 ret[0] = collections.Counter({k+1:v for k,v in (left[0]+right[0]).iteritems()})45 return result46 47 return iter_dfs(distance, root)48 49 505152import collections53 54 55class Solution2(object):56 def countPairs(self, root, distance):57 """58 :type root: TreeNode59 :type distance: int60 :rtype: int61 """62 def dfs(distance, node):63 if not node:64 return 0, collections.Counter()65 if not node.left and not node.right:66 return 0, collections.Counter([0])67 left, right = dfs(distance, node.left), dfs(distance, node.right)68 result = left[0]+right[0]69 for left_d, left_c in left[1].iteritems():70 for right_d,right_c in right[1].iteritems():71 if left_d+right_d+2 <= distance:72 result += left_c*right_c73 return result, collections.Counter({k+1:v for k,v in (left[1]+right[1]).iteritems()})74 75 return dfs(distance, root)[0]76