257. 二叉树的所有路径器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def __init__(self):
self.path_list = []
self.path = []
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
self.path.append(str(root.val) )
if root.left==None and root.right==None: # 叶子结点
self.path_list.append('->'.join(self.path))
return self.path_list
if root.left:
self.binaryTreePaths(root.left)
self.path.pop() # 回溯 弹出
if root.right:
self.binaryTreePaths(root.right)
self.path.pop()
print(self.path)
return self.path_list