以下是一個二元搜索函數(一個根有一個左邊和一個右邊的孩子),我不太明白。在代碼中,它返回一個列表,該列表是二叉樹中最長的路徑。但是對於零件: 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):
如何理解二叉樹中的以下遞歸函數?
如何比較兩個遞歸調用?例如,如果樹是
1 /\ 2
list_longest_path(node.right)
肯定會返回[]
。但是,您如何將list_longest_path(2)
與[]
進行比較?
有人幫助會很好。
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