Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 非二叉树高度(优化) 介绍_Python_Python 3.x_Tree - Fatal编程技术网

Python 非二叉树高度(优化) 介绍

Python 非二叉树高度(优化) 介绍,python,python-3.x,tree,Python,Python 3.x,Tree,因此,我正在学习一门关于edX的课程,并一直在做这项实践作业 最好的部分是3个小时,但我仍然找不到一个方法来实现这个方法 无需花费很长时间,自动平地机也不会超时 我尝试了3种不同的方法,它们都做了相同的事情。 包括2个递归方法和1个非递归方法(我的最新版本) 我认为我的代码存在的问题是,查找子节点的方法需要很长时间,因为它必须迭代整个节点列表 输入输出格式 输入在第一行包括N,这是第2行给出的列表的大小 例如: 要从中构建树: 数组中的每个值都是指向数组中另一个索引的指针,因此在上面的示例中,0

因此,我正在学习一门关于edX的课程,并一直在做这项实践作业 最好的部分是3个小时,但我仍然找不到一个方法来实现这个方法 无需花费很长时间,自动平地机也不会超时

我尝试了3种不同的方法,它们都做了相同的事情。 包括2个递归方法和1个非递归方法(我的最新版本)

我认为我的代码存在的问题是,查找子节点的方法需要很长时间,因为它必须迭代整个节点列表

输入输出格式 输入在第一行包括N,这是第2行给出的列表的大小

例如:

要从中构建树: 数组中的每个值都是指向数组中另一个索引的指针,因此在上面的示例中,0是-1(索引0)的子节点。因为-1不指向其他索引,所以它是根节点

示例中的树有根节点-1,它有两个子节点0(索引1)和0(索引3)。索引为1的0没有子级,索引为3的0有一个子级:3(索引4),而该子级又只有一个子级,即4(索引2)

上述输入产生的输出为4。这是因为包含-1(根节点)、0、3和4的分支的最大高度为4,而另一个分支的高度(-1和0)为2

如果你需要更详细的解释,那么我可以在评论中再举一个例子

输出是树的最大高度。输入的大小增加到100000,这是我遇到问题的地方,因为它必须在正好3秒钟内完成输入

我的代码 这是我最新的非递归方法,我认为这是我做的最快的(仍然不够快)。我使用了网站上的初学者,我还将在代码下面包含该初学者。无论如何,谢谢你的帮助

我的代码:

# python3

import sys, threading
sys.setrecursionlimit(10**7) # max depth of recursion
threading.stack_size(2**27)  # new thread will get stack of such size

def height(node, parent_list):
        h = 0
        while not node == -1:
                h = h + 1
                node = parent_list[node]
        return h + 1

def search_bottom_nodes(parent_list):
        bottom_nodes = []
        for index, value in enumerate(parent_list):
                children = [i for i, x in enumerate(parent_list) if x == index]
                if len(children) == 0:
                        bottom_nodes.append(value)

        return bottom_nodes

class TreeHeight:
        def read(self):
                self.n = int(sys.stdin.readline())
                self.parent = list(map(int, sys.stdin.readline().split()))

        def compute_height(self):
                # Replace this code with a faster implementation
                bottom_nodes = search_bottom_nodes(self.parent)
                h = 0
                for index, value in enumerate(bottom_nodes):
                        h = max(height(value, self.parent), h)
                return h


def main():
  tree = TreeHeight()
  tree.read()
  print(tree.compute_height())

threading.Thread(target=main).start()
edX启动器:

# python3

import sys, threading
sys.setrecursionlimit(10**7) # max depth of recursion
threading.stack_size(2**27)  # new thread will get stack of such size

class TreeHeight:
        def read(self):
                self.n = int(sys.stdin.readline())
                self.parent = list(map(int, sys.stdin.readline().split()))

        def compute_height(self):
                # Replace this code with a faster implementation
                maxHeight = 0
                for vertex in range(self.n):
                        height = 0
                        i = vertex
                        while i != -1:
                                height += 1
                                i = self.parent[i]
                        maxHeight = max(maxHeight, height);
                return maxHeight;

def main():
  tree = TreeHeight()
  tree.read()
  print(tree.compute_height())

threading.Thread(target=main).start()

只需在dict中缓存先前计算的节点高度,并在它们被引用为父节点时重用它们

import sys, threading
sys.setrecursionlimit(10**7) # max depth of recursion
threading.stack_size(2**27)  # new thread will get stack of such size

class TreeHeight:
    def height(self, node):
        if node == -1:
            return 0
        if self.parent[node] in self.heights:
            self.heights[node] = self.heights[self.parent[node]] + 1
        else:
            self.heights[node] = self.height(self.parent[node]) + 1
        return self.heights[node]

    def read(self):
        self.n = int(sys.stdin.readline())
        self.parent = list(map(int, sys.stdin.readline().split()))
        self.heights = {}

    def compute_height(self):
        maxHeight = 0
        for vertex in range(self.n):
            maxHeight = max(maxHeight, self.height(vertex))
        return maxHeight;

def main():
    tree = TreeHeight()
    tree.read()
    print(tree.compute_height())

threading.Thread(target=main).start()
给定与您的问题相同的输入,此(和您的原始代码)输出:


我真的不明白你是如何从列表中构造一棵树的。你能一步一步地发布详细的规则吗?是的,预期的输出在这里会很有帮助,你对如何构建树的解释不是greatOkay我添加了一个更好的解释,希望有帮助。谢谢你的回答,这是我喜欢编程的原因之一。在过去的两天里,我一直在努力解决这个问题(决定不放弃),课程没有给出任何解释或任何东西,所以我必须自己找出格式和所有内容。这个解决方案让我大吃一惊,因为它太简单了!!作为一名程序员,我还有很长的路要走。很高兴能提供帮助。我完全同意。找出给定问题的最佳算法的过程就是我们热爱编程的原因。:-)
import sys, threading
sys.setrecursionlimit(10**7) # max depth of recursion
threading.stack_size(2**27)  # new thread will get stack of such size

class TreeHeight:
    def height(self, node):
        if node == -1:
            return 0
        if self.parent[node] in self.heights:
            self.heights[node] = self.heights[self.parent[node]] + 1
        else:
            self.heights[node] = self.height(self.parent[node]) + 1
        return self.heights[node]

    def read(self):
        self.n = int(sys.stdin.readline())
        self.parent = list(map(int, sys.stdin.readline().split()))
        self.heights = {}

    def compute_height(self):
        maxHeight = 0
        for vertex in range(self.n):
            maxHeight = max(maxHeight, self.height(vertex))
        return maxHeight;

def main():
    tree = TreeHeight()
    tree.read()
    print(tree.compute_height())

threading.Thread(target=main).start()
4