-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_tree_path.py
More file actions
43 lines (28 loc) · 924 Bytes
/
binary_tree_path.py
File metadata and controls
43 lines (28 loc) · 924 Bytes
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
from pathlib import Path
import sys
sys.path.append(str(Path(__file__).resolve().parent.parent))
from binary_tree import create_binary_tree
class Solution:
def binaryTreePaths(self, root):
if root is None:
return []
result = []
def backtrack(node, solution):
if node is None:
return
solution.append(str(node.val))
if not node.left and not node.right:
result.append("->".join(solution))
backtrack(node.left, solution)
backtrack(node.right, solution)
solution.pop()
backtrack(root, [])
return result
if __name__ == "__main__":
root = [1, 2, 3, None, 5]
bt = create_binary_tree(root)
solution = Solution()
result = solution.binaryTreePaths(bt)
assert result == ["1->2->5", "1->3"]
print(result)
print("Test Case 1 Passed!")