【发布时间】:2016-06-24 14:00:03
【问题描述】:
我有一个 nTree(n 维),我想计算包含特定深度数据点的节点数。这是我尝试使用的树结构和函数:
class nTree:
def initialize(self, hypercube_coordinates, depth=0):
self.data = [] #holds the data - this tells if the node is empty or not
self.children = []
self.depth = depth
self.hypercube = hypercube #coordinates
#a bit inefficient since we are theoretically visiting each node
#can be optimized later
def count_nodes_at_level(self, depth):
count = 0
for child in self.children:
if child.depth == depth:
count += child.count_nodes_at_level(self.depth)
else:
child.count_nodes_at_level(depth)
return count
我知道我的方法效率有点低,但我希望它首先可以工作,然后我可以优化它。我已经阅读了关于这个问题的另一篇文章,我的方法与其他文章的方法非常相似,但它不适用于 nTree。就我而言,我有 64 个孩子/父母。另外,我不确定 PreOrder、PostOrder、InOrder 或 BreadthFirst 遍历中的任何一个是否会起作用,因为我无法引用左或右子子项。对改进/使该方法有效的任何建议?
【问题讨论】:
标签: python data-structures tree tree-traversal