python中通用树中的节点计数

python中通用树中的节点计数,python,tree,Python,Tree,我创建了一个不是二叉树的树结构,并且很难获得正确的节点数 class TreeNode(object): def __init__(self, name='root', children=None,Parent=[]): self.Name = name self.Parents=Parent self.Children = [] if children is not None: for child in children:

我创建了一个不是二叉树的树结构,并且很难获得正确的节点数

class TreeNode(object):
  def __init__(self, name='root', children=None,Parent=[]):
    self.Name = name
    self.Parents=Parent

    self.Children = []
    if children is not None:
        for child in children:
            self.add_child(child.Name)

 def __repr__(self):
   return self.Name

 def add_child(self, node):    
  self.Children.append(node)
这是我最近一次尝试计算树中的节点数

def countNodes(Tree):      

   for Child in Tree.Children:
      return countNodes(Child)+1

   return 1
有人能解释一下为什么这不起作用吗?
编辑:我应该澄清一下,当我说“不起作用”时,它给了我一个完全错误的图表中节点数的计数

您的
countNodes
功能不正常。父节点可以有两个子节点,如果在
for
循环中放入
return
语句,它将在第一个子节点计数时返回,第二个子节点计数将丢失。您需要这样做:

def countNodes(Tree):      
   count = 1
   for Child in Tree.Children:
      count +=  countNodes(Child)
   return count
只需补充一下@levi遗漏了一个根为None的边缘情况

因此,修改后的代码将是:

def numNodes(root):
    if root == None:
        return 0 
    node = 1
    for child in root.children:
        node = node + numNodes(child)
    return node

怎么了?它给了您一个错误的答案或一个执行错误?计数的数字完全错误小心使用列表作为默认参数,例如
Parent=[]
。是的,这就是我所缺少的。感谢就像一种魅力