首页 > 解决方案 > 函数调用后我的计数器没有重置

问题描述

嘿,各位程序员,这里是 Python(3) 学习者。

这次我的问题是,我的变量应该跟踪二叉树中的节点数量(由字典和列表的组合表示),保持先前函数调用的数量,而我需要重置它。

我的输出是 3 个单独的函数调用: 0 3 7 我们可以看到第二棵树中的节点数量被保留并添加到第三棵树的数量中。虽然它必须是:0 3 4 我的代码:

nodes=0

def give_node(tree):
    global nodes
    if tree==None: #If the 'tree' begins with the value None, then there are no nodes.
        nodes=0
        return nodes
    elif len(tree)==2: #If the dictionary has 2 items, then it's a leaf.
        nodes+=1
    elif len(tree)==3: #If the dictionary has 3 items, it's a parent with at least 1 child.
        nodes+=1
    if not(None == tree['children'][0]):
        give_node(tree['children'][0])
    if not(None == tree['children'][1]):
        give_node(tree['children'][1])
        return nodes

print(give_node(None))

print(give_node({'name': 'GAS', 'grade': 0.8, 'children': [{'name': 'CSA', 'grade': 0.5}, {'name': 'IP', 'grade': 0.99}]}))

print(give_node({'name': 'GAS', 'grade': 0.8, 'children': [{'name': 'CSA', 'grade': 0.5, 'children': [None, {'name': 'TA', 'grade': 0.6}]}, {'name': 'IP', 'grade': 0.99}]}))

附言。我必须做一个递归函数 图片方便查看

标签: python-3.xoutputcounter

解决方案


推荐阅读