- Binary Tree Paths Easy
897
68
Favorite
Share Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/
2 3
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
思路:dfs 记录每条线的数组 代码:python3
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
if not root: return []
arr=[]
def dfs(root,ar):
subAr=ar[:]
if not root:return
if not root.left and not root.right:
subAr.append(str(root.val))
arr.append(subAr)
else:
subAr.append(str(root.val))
dfs(root.left,subAr)
dfs(root.right,subAr)
dfs(root,[])
result=[]
for a in arr:
result.append('->'.join(a))
return result
复制代码