问题描述
https://leetcode.cn/problems/binary-tree-paths/description/
解题思路
叶子结点时,添加到结果序列即可。
代码
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]: res = [] def dfs(root, cur): if root is None: return cur += str(root.val) if root.left is None and root.right is None: res.append(cur) dfs(root.left, cur+'->' if root.left is not None else cur) dfs(root.right, cur+'->' if root.right is not None else cur) dfs(root, '') return res
标签:None,right,cur,self,路径,二叉树,root,257,left From: https://www.cnblogs.com/bjfu-vth/p/17071170.html