您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

优化在Python中查找二叉树的直径

优化在Python中查找二叉树的直径

Python支持多个返回值,因此您不需要像C或C ++中那样的指针参数。这是代码的翻译:

def diameter_height(node):
    if node is None:
        return 0, 0
    ld, lh = diameter_height(node.left)
    rd, rh = diameter_height(node.right)
    return max(lh + rh + 1, ld, rd), 1 + max(lh, rh)

def find_tree_diameter(node):
    d, _ = diameter_height(node)
    return d

函数diameter_height返回树的直径和高度,并find_tree_diameter使用它仅计算直径(通过丢弃高度)。

无论树的形状如何,函数均为O(n)。在最坏的情况下,由于重复的高度计算,树非常不平衡时,原始函数为O(n ^ 2)。

python 2022/1/1 18:36:35 有440人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶