思路:DFS。
- 注意格式化输出,可以先用字符串拼接起来,再append到list中。
- 注意判定条件,当遍历到叶子结点时就是一条完整路径了,这时就可以append到list中了。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
def dfs(root, res, path_str):
if not root:
return []
path_str += str(root.val)
if (not root.left) and (not root.right):
res.append(path_str)
path_str += '->'
dfs(root.left, res, path_str)
dfs(root.right, res, path_str)
return res
if not root:
return []
res = []
path_str = ''
return dfs(root, res, path_str)