原题链接:https://leetcode.com/problems/binary-tree-paths/
两种做法,iterative or recursive. 遍历的做法更快一些也更简单。
def binaryTreePaths(self, root: TreeNode) -> List[str]:
self.out = []
if not root:
return self.out
level = [(root, str(root.val))]
while level:
node, path = level.pop()
if not node.left and not node.right:
self.out.append(path)
if node.left:
level.append((node.left, path+'->'+str(node.left.val)))
if node.right:
level.append((node.right, path+'->'+str(node.right.val)))
return self.out
网友评论