题目
给出一个二叉树,输出根节点到叶节点的路径的集合。输出样式为:
[
“1->2->3,”
“4->5”,
]。
Python题解
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
def dfs(root, item, res):
if not root.left and not root.right:
res.append(item + str(root.val))
if root.left is not None:
dfs(root.left, item + str(root.val) + "->", res)
if root.right is not None:
dfs(root.right, item + str(root.val) + "->", res)
if not root:
return []
item, res = "", []
dfs(root, item, res)
return res