-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinaryTreePaths.py
More file actions
41 lines (33 loc) · 923 Bytes
/
Copy pathbinaryTreePaths.py
File metadata and controls
41 lines (33 loc) · 923 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
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
"""
@FileName : binaryTreePaths.py
@Author : 56
@Description: https://leetcode-cn.com/problems/binary-tree-paths/
"""
from typing import List
class TreeNode:
# Definition for a binary tree node.
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
if root is None:
return []
res = []
paths = []
def dfs(node: TreeNode):
paths.append(str(node.val))
if node.left is None and node.right is None:
res.append('->'.join(paths))
paths.pop()
return
if node.left:
dfs(node.left)
if node.right:
dfs(node.right)
paths.pop()
dfs(root)
return res