-
Notifications
You must be signed in to change notification settings - Fork 0
/
0257.py
39 lines (36 loc) · 1.22 KB
/
0257.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def binaryTreePaths1(self, root: TreeNode) -> List[str]:
if not root:
return []
def dfs(root, tmp_path, res_paths):
if not root:
return
if not root.left and not root.right:
tmp_path += str(root.val)
res_paths.append(tmp_path)
else:
tmp_path += str(root.val) + "->"
dfs(root.left, tmp_path, res_paths)
dfs(root.right, tmp_path, res_paths)
return res_paths
return dfs(root, "", [])
def binaryTreePaths(self, root: TreeNode) -> List[str]:
if not root:
return root
self.res = []
def helper(root, path):
if not root:
return
if not root.left and not root.right:
path += str(root.val)
self.res.append(path)
helper(root.left, path + str(root.val) + "->")
helper(root.right, path + str(root.val) + "->")
helper(root, "")
return self.res