从递归函数返回字典 - python

我有一个二进制搜索树,其中每个节点代表一个游戏长度。我必须返回一个字典,其中的键是游戏的长度,值是该长度的游戏数。递归调用遍历树中的每个节点,但返回错误的字典。我很肯定问题是我如何退还字典。任何帮助将不胜感激

game_len = {}
if not node.children:
    key = len(node.possible_next_moves())
    if key not in game_len:
        game_len[key] = 1
    else:
        game_len[key] += 1
else:
    key = len(node.possible_next_moves())
    if key not in game_len:
        game_len[key] = 1
    else:
        game_len[key] += 1
    [game_lengths(child) for child in node.children] 
return game_len

python大神给出的解决方案

通常,有两种方法可以处理递归算法的返回值。您可以从递归调用中收集返回值并将它们组合起来,或者可以传递一个额外的可变参数,递归调用可以对其进行修改。我认为后者在这种情况下可能是最好的,因为字典很容易就位,但是合并起来却不那么容易:

def game_lengths(node, result=None):
    if result is None:
        result = {}

    #... add a value to the result dict, handle base cases, etc.

    for child in node.children:
        game_lengths(child, result)

    return result