-
Notifications
You must be signed in to change notification settings - Fork 0
/
110.py
64 lines (47 loc) · 1.18 KB
/
110.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
58
59
60
61
62
63
64
"""
Problem:
Given a binary tree, return all paths from the root to leaves.
For example, given the tree
1
/ \
2 3
/ \
4 5
it should return [[1, 2], [1, 3, 4], [1, 3, 5]].
"""
from typing import List
from DataStructures.Tree import BinaryTree, Node
def get_paths_helper(node: Node, paths: List[int], curr_path: List[int]) -> None:
if not node.left and not node.right:
# leaf node
curr_path.append(node.val)
paths.append([*curr_path])
curr_path.pop()
return
# non-leaf node
curr_path.append(node.val)
if node.left:
get_paths_helper(node.left, paths, curr_path)
if node.right:
get_paths_helper(node.right, paths, curr_path)
curr_path.pop()
def get_paths(tree: BinaryTree):
if not tree.root:
return []
paths = []
get_paths_helper(tree.root, paths, [])
return paths
if __name__ == "__main__":
tree = BinaryTree()
tree.root = Node(1)
tree.root.left = Node(2)
tree.root.right = Node(3)
tree.root.right.left = Node(4)
tree.root.right.right = Node(5)
print(tree)
print(get_paths(tree))
"""
SPECS:
TIME COMPLEXITY: O(n)
SPACE COMPLEXITY: O(log(n))
"""