forked from wuduhren/leetcode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-tree-paths.py
More file actions
executable file
·42 lines (30 loc) · 1.09 KB
/
binary-tree-paths.py
File metadata and controls
executable file
·42 lines (30 loc) · 1.09 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
class Solution(object):
def binaryTreePaths(self, root):
if not root: return []
arrow = '->'
ans = []
stack = []
stack.append((root, ''))
while stack:
node, path = stack.pop()
path += arrow+str(node.val) if path else str(node.val) #add arrow except beginnings
if not node.left and not node.right: ans.append(path) #if isLeaf, append path.
if node.left: stack.append((node.left, path))
if node.right: stack.append((node.right, path))
return ans
"""
Time: O(N)
Space: O(N)
Standard BFS.
"""
class Solution(object):
def binaryTreePaths(self, root):
q = collections.deque([(root, '')])
ans = []
while q:
node, path = q.popleft()
path = (path+'->'+str(node.val)) if path else str(node.val)
if node.left: q.append((node.left, path))
if node.right: q.append((node.right, path))
if not node.left and not node.right: ans.append(path)
return ans