【问题标题】:Counting the number of nodes containing data at a specific level - nTree计算包含特定级别数据的节点数 - nTree
【发布时间】: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


    【解决方案1】:

    问题已解决。对于任何寻求解决方案的人来说,方法是:

    #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) 的时间内做到这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-13
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多