【发布时间】:2016-08-16 19:38:59
【问题描述】:
下面是一个我不太理解的二分搜索函数(一个根有一个左子和一个右子)。在代码中,它返回一个列表,该列表是二叉树中最长的路径。但是对于这部分:
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
【问题讨论】:
标签: python python-3.x recursion binary-tree binary-search-tree