-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path257_Binary_Tree_Paths.py
More file actions
51 lines (46 loc) · 1.5 KB
/
Copy path257_Binary_Tree_Paths.py
File metadata and controls
51 lines (46 loc) · 1.5 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
# Author: cym
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# def binaryTreePaths(self, root):
# """
# :type root: TreeNode
# :rtype: List[str]
# """
# def preOrder(root, path, ans):
# if root.left is None and root.right is None:
# ans.append(path + str(root.val))
# return
# if root.left:
# preOrder(root.left, path + str(root.val) + '->', ans)
# if root.right:
# preOrder(root.right, path + str(root.val) + '->', ans)
# if root is None:
# return []
# path = ""
# ans = []
# preOrder(root, path, ans)
# return ans
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if root is None:
return []
path = ""
ans = []
self.preOrder(root, path, ans)
return ans
def preOrder(self, root, path, ans):
if root.left is None and root.right is None:
ans.append(path + str(root.val))
return
if root.left:
self.preOrder(root.left, path + str(root.val) + '->', ans)
if root.right:
self.preOrder(root.right, path + str(root.val) + '->', ans)