如何在python中计算父节点之后的所有节点

2024-09-30 01:30:16 发布

您现在位置:Python中文网/ 问答频道 /正文

enter image description here

在给定的树中,当我们通过节点--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)

但有了这个,我只计算它的子节点


Tags: nonenodereturnif节点isdefcount
2条回答

正如其他人所说,您的代码是为具有lchildrchild成员的节点实例设计的,但是图中的树有一个具有3个子节点的节点,因此它不能表示为这样的节点

您需要不同的节点类定义:

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())

您的代码在Binary Tree上正确运行,但是Tree of your question不是Binary Tree,您需要一种不同的方法。您需要为类中的每个节点定义list of child,并使用以下代码:

def count(node):
    if node is None:
        return 0
    count = 1
    for child in node_child
        count += count(child)
    return count

相关问题 更多 >

    热门问题