Skip to content

Commit 8f03873

Browse files
committed
Create binary-tree-paths.py
1 parent 74f02df commit 8f03873

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Python/binary-tree-paths.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Time: O(n * h)
2+
# Space: O(h)
3+
#
4+
# Definition for a binary tree node.
5+
# class TreeNode:
6+
# def __init__(self, x):
7+
# self.val = x
8+
# self.left = None
9+
# self.right = None
10+
11+
class Solution:
12+
# @param {TreeNode} root
13+
# @return {string[]}
14+
def binaryTreePaths(self, root):
15+
result, path = [], []
16+
self.binaryTreePathsRecu(root, path, result)
17+
return result
18+
19+
def binaryTreePathsRecu(self, node, path, result):
20+
if node is None:
21+
return
22+
23+
if node.left is node.right is None:
24+
ans = ""
25+
for n in path:
26+
ans += str(n.val) + "->"
27+
resault.append(ans + str(node.val))
28+
29+
if node.left:
30+
path.append(node)
31+
self.binaryTreePathsRecu(node.left, path, result)
32+
path.pop()
33+
34+
if node.right:
35+
path.append(node)
36+
self.binaryTreePathsRecu(node.right, path, result)
37+
path.pop()

0 commit comments

Comments
 (0)