如何统计python中父节点之后的所有节点
How to count all the nodes after parent node in python
在给定的树中,当我们通过 node-- 2 时输出为 5,它计算 2 之后的所有节点,
4-5-6-7-8
def count(node):
if node is None:
return 0
return 1+count(node.lchild)+count(node.rchild)
但是有了这个,我只计算它的子节点
您的代码在 Binary Tree
上运行正确,但 Tree of your question
不是 Binary Tree
,您需要不同的方法。您需要为 class 中的每个节点定义 list of child
并使用此代码:
def count(node):
if node is None:
return 0
count = 1
for child in node_child
count += count(child)
return count
正如其他人所说,您的代码是为具有 lchild
和 rchild
成员的节点实例设计的,但是图片中的树有一个具有 3 children 的节点,所以它不能表示为这样的节点。
您需要对节点进行不同的定义 class:
class Node:
def __init__(self, value, *children):
self.value = value
self.children = children
然后我会将 count
定义为 class 的 方法 ,而不是 stand-alone 函数:
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())
在给定的树中,当我们通过 node-- 2 时输出为 5,它计算 2 之后的所有节点, 4-5-6-7-8
def count(node):
if node is None:
return 0
return 1+count(node.lchild)+count(node.rchild)
但是有了这个,我只计算它的子节点
您的代码在 Binary Tree
上运行正确,但 Tree of your question
不是 Binary Tree
,您需要不同的方法。您需要为 class 中的每个节点定义 list of child
并使用此代码:
def count(node):
if node is None:
return 0
count = 1
for child in node_child
count += count(child)
return count
正如其他人所说,您的代码是为具有 lchild
和 rchild
成员的节点实例设计的,但是图片中的树有一个具有 3 children 的节点,所以它不能表示为这样的节点。
您需要对节点进行不同的定义 class:
class Node:
def __init__(self, value, *children):
self.value = value
self.children = children
然后我会将 count
定义为 class 的 方法 ,而不是 stand-alone 函数:
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())