簡體   English   中英

如何列出二叉樹中最長的路徑?

[英]How to list the longest path in binary tree?

在這里,我們嘗試列出二叉樹中最長的路徑。 例如,

list_longest_path(None)

[]

list_longest_path(BinaryTree(5))

[5]

b1 = BinaryTree(7)

b2 = BinaryTree(3, BinaryTree(2), None)

b3 = BinaryTree(5, b2, b1)

list_longest_path(b3)

[5, 3, 2]

我的代碼在底部。 顯然,代碼返回樹中的每個節點。 在這里,我很難同時使用max()時如何生成所有列表?

class BinaryTree:
"""
A Binary Tree, i.e. arity 2.

=== Attributes ===
@param object data: data for this binary tree node
@param BinaryTree|None left: left child of this binary tree node
@param BinaryTree|None right: right child of this binary tree node
"""

def __init__(self, data, left=None, right=None):
    """
    Create BinaryTree self with data and children left and right.

    @param BinaryTree self: this binary tree
    @param object data: data of this node
    @param BinaryTree|None left: left child
    @param BinaryTree|None right: right child
    @rtype: None
    """
    self.data, self.left, self.right = data, left, right

def __eq__(self, other):
    """
    Return whether BinaryTree self is equivalent to other.

    @param BinaryTree self: this binary tree
    @param Any other: object to check equivalence to self
    @rtype: bool

    >>> BinaryTree(7).__eq__("seven")
    False
    >>> b1 = BinaryTree(7, BinaryTree(5))
    >>> b1.__eq__(BinaryTree(7, BinaryTree(5), None))
    True
    """
    return (type(self) == type(other) and
            self.data == other.data and
            (self.left, self.right) == (other.left, other.right))

def __repr__(self):
    """
    Represent BinaryTree (self) as a string that can be evaluated to
    produce an equivalent BinaryTree.

    @param BinaryTree self: this binary tree
    @rtype: str

    >>> BinaryTree(1, BinaryTree(2), BinaryTree(3))
    BinaryTree(1, BinaryTree(2, None, None), BinaryTree(3, None, None))
    """
    return "BinaryTree({}, {}, {})".format(repr(self.data),
                                           repr(self.left),
                                           repr(self.right))

def __str__(self, indent=""):
    """
    Return a user-friendly string representing BinaryTree (self)
    inorder.  Indent by indent.

    >>> b = BinaryTree(1, BinaryTree(2, BinaryTree(3)), BinaryTree(4))
    >>> print(b)
        4
    1
        2
            3
    <BLANKLINE>
    """
    right_tree = (self.right.__str__(
        indent + "    ") if self.right else "")
    left_tree = self.left.__str__(indent + "    ") if self.left else ""
    return (right_tree + "{}{}\n".format(indent, str(self.data)) +
            left_tree)

def __contains__(self, value):
    """
    Return whether tree rooted at node contains value.

    @param BinaryTree self: binary tree to search for value
    @param object value: value to search for
    @rtype: bool

    >>> BinaryTree(5, BinaryTree(7), BinaryTree(9)).__contains__(7)
    True
    """
    return (self.data == value or
            (self.left and value in self.left) or
            (self.right and value in self.right))

def list_longest_path(node):
"""
List the data in a longest path of node.

@param BinaryTree|None node: tree to list longest path of
@rtype: list[object]

>>> list_longest_path(None)
[]
>>> list_longest_path(BinaryTree(5))
[5]
>>> b1 = BinaryTree(7)
>>> b2 = BinaryTree(3, BinaryTree(2), None)
>>> b3 = BinaryTree(5, b2, b1)
>>> list_longest_path(b3)
[5, 3, 2]
"""
if node is None:
    return []
elif not node.left and not node.right:
    return [node]
else:
    return [node]+list_longest_path(node.left)+list_longest_path(node.right)

樹中最長的路徑稱為“ 直徑 ”。 因此,您正在尋找類似“ python樹直徑計算器”的東西

您可以在此處查看算法的實現:

http://www.geeksforgeeks.org/diameter-of-a-binary-tree/

和這里:

http://tech-queries.blogspot.com.br/2010/09/diameter-of-tree-in-on.html


由於此網站僅包含C和JAVA的代碼,因此您可以在此處查看一些pythonic編碼思想:

優化在Python中查找二叉樹的直徑

這是一個Python函數,它將返回路徑:

def list_longest_path(root):
    if not root:
        return []

    l = list_longest_path(root.left)
    r = list_longest_path(root.right)

    if len(l) > len(r):
        return [root] + l
    else:
        return [root] + r

在您的代碼中,無需檢查左孩子或右孩子是否存在,因為您的函數無論如何都會返回列表。 但是,您需要做的是檢查從子級返回的列表的長度,然后選擇更長的列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM