-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbt_path_lc257.py
57 lines (43 loc) · 1.04 KB
/
bt_path_lc257.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# Given a binary tree, return all root-to-leaf paths.
# For example, given the following binary tree:
# 1
# / \
# 2 3
# \
# 5
# All root-to-leaf paths are:
# ["1->2->5", "1->3"]
class Node(object):
"""Simple node class."""
def __init__(self, val):
"""."""
self.val = val
self.left = None
self.right = None
def __repr__(self):
"""."""
return str(self.val)
def path(head):
"""LC 257."""
result = []
_path(head, result)
return result
def _path(node, result, temp=None):
"""."""
if not temp:
temp = []
if not node.left and not node.right:
result.append(temp + [node])
return
if node.left:
_path(node.left, result, temp + [node])
if node.right:
_path(node.right, result, temp + [node])
if __name__ == "__main__":
head = Node(20)
head.left = Node(10)
head.left.left = Node(5)
head.left.right = Node(15)
head.right = Node(30)
head.right.left = Node(25)
head.right.right = Node(35)