Binary Tree Paths LeetCode solution in Python

1
class Solution:
2
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
3

4
# DFS solution
5
output = []
6
stack = [(root, "")]
7

8
while stack:
9
node, path = stack.pop()
10
path += str(node.val)
11

12
if not node.left and not node.right:
13
output.append(path)
14

15
path += "->"
16
if node.left:
17
stack.append((node.left, path))
18
if node.right:
19
stack.append((node.right, path))
20

21
return output

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0