[Python] How to comprehend the following recursive function in binary tree?

Discussão em 'Python' iniciado por Stack, Janeiro 28, 2025.

  1. Stack

    Stack Membro Participativo

    The following is a Binary search function (a root has a left and a right child) which I don't quite comprehend. In the code it returns a list that is the longest path in the binary tree. However for the part:

    return_path_left = list_longest_path(node.left)
    return_path_right = list_longest_path(node.right)
    if len(return_path_left) > len(return_path_right):


    how can you compare two recursive call? For example, if the tree is

    1
    / \
    2


    list_longest_path(node.right) will surely return []. But how do you compare list_longest_path(2) with []?

    Someone help will be great.

    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 []
    else:
    return_path_left = list_longest_path(node.left)
    return_path_right = list_longest_path(node.right)
    if len(return_path_left) > len(return_path_right):
    return [node.data] + return_path_left
    else:
    return [node.data] + return_path_right

    Continue reading...

Compartilhe esta Página