class Node:
def __init__(self, value, *children):
self.value = value
self.children = children
然后我将count定义为该类的方法,而不是独立函数:
class Node
# ...
def count(self):
return sum(1 + child.count() for child in self.children)
运行示例:
# Create the tree as pictured in the question
root = Node(1,
Node(2,
Node(4),
Node(5,
Node(7),
Node(8)
),
Node(6)),
Node(3)
)
# Select the node with value 2 (at left of root) and call the `count` method:
print(root.children[0].count())
正如其他人所说,您的代码是为具有
lchild
和rchild
成员的节点实例设计的,但是图中的树有一个具有3个子节点的节点,因此它不能表示为这样的节点您需要不同的节点类定义:
然后我将
count
定义为该类的方法,而不是独立函数:运行示例:
您的代码在
Binary Tree
上正确运行,但是Tree of your question
不是Binary Tree
,您需要一种不同的方法。您需要为类中的每个节点定义list of child
,并使用以下代码:相关问题 更多 >
编程相关推荐