方法1
Traverse
Time complexity: O(n)
Space complexity: O(n)
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
if root is None:
return []
res = []
self.dfs(root, [str(root.val)], res)
return res
def dfs(self, root, path, paths):
if root.left is None and root.right is None:
paths.append('->'.join(path))
return
if root.left:
path.append(str(root.left.val))
self.dfs(root.left, path, paths)
path.pop()
if root.right:
path.append(str(root.right.val))
self.dfs(root.right, path, paths)
path.pop()