首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >统计包含特定级别数据的节点数-- nTree

统计包含特定级别数据的节点数-- nTree
EN

Stack Overflow用户
提问于 2016-06-24 22:00:03
回答 1查看 477关注 0票数 0

我有一个维度(n维),我想要计算在特定深度包含数据点的节点的数量。下面是我尝试使用的树结构和函数:

代码语言:javascript
复制
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遍历,因为我不能引用左或右子对象。对于改进/使该方法有效,有什么建议?

EN

回答 1

Stack Overflow用户

发布于 2016-06-24 23:33:00

问题已修复。对于任何正在寻找解决方案的人来说,这里是一个方法:

代码语言:javascript
复制
#countNodesAtLevel - returns the number of non-empty nodes at a given level
#Parameters:
#    depth - depth at which we are counting

def _countNodesAtLevel(self, depth, count=0):

    #root level = 0, return only 1 for the data
    if depth == 0 and self.data:
        return 1
    else:
        for child in self.children:
            if child.depth == depth and child.data:
                count+=1
                count+=child.countNodesAtLevel(depth)
            else:
                count+=child.countNodesAtLevel(depth)
    return count

#USER FUNCTION
#countNodesAtLevel - returns the number of non-empty nodes at a given level
def countNodesAtLevel(self, depth):
    count = self._countNodesAtLevel(depth)
    print(count) 

此方法使用深度优先遍历模型,因此它检查树中的每个节点。我相信有更好的方法可以在少于O(n)的时间内做到这一点。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38015250

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档