在这棵树中:
我不确定为什么会出现
谢谢!
a
/ \
b d
/ / \
c e f
/
g
从根节点开始的最长路径是a-d-f-g
这里是我的翻译:
class Node:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def print_path(root):
if not root:
return []
if root.left is None:
return [root.val].append(print_path(root.right))
elif root.right is None:
return [root.val].append(print_path(root.left))
elif (root.right is None) and (root.left is None):
return [root.val]
else:
return argmax([root.val].append(print_path(root.left)), [root.val].append(print_path(root.right)))
def argmax(lst1, lst2):
return lst1 if len(lst1) > len(lst2) else lst2
if __name__ == '__main__':
root_node = Node('a')
root_node.left = Node('b')
root_node.right = Node('c')
root_node.right.right = Node('f')
print print_path(root_node)
main()
函数中的树并不是我展示的那个例子。对于这棵树,预期结果应该是a-c-f
。该树如下所示:
a
/ \
b c
\
f
现在,我获得
TypeError: object of type 'NoneType' has no len()
我不确定为什么会出现
None
,因为我已经有了基本情况。谢谢!
a-c-f
的树)而不是其他树,那么这将是一个更容易的问题。 - GlenPeterson