输入:
1
/ \
2 3
\
5
输出: ["1->2->5", "1->3"]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
使用DFS探索整棵树.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
res = []
def dfs(node, path):
if node is None:
return
path.append(str(node.val))
if node.left is None and node.right is None:
res.append('->'.join(path))
else:
dfs(node.left, path)
dfs(node.right, path)
path.pop()
dfs(root, [])
return res