leetcode刷题笔记——二叉树的所有路径——f““函数的用法——python3

题目:

leetcode刷题笔记——二叉树的所有路径——f““函数的用法——python3_第1张图片

 答案:

class Solution:
    def binaryTreePaths(self, root: TreeNode, prefix="") -> List[str]:
        if root is None:
            return []
                
        if prefix == "":
            new_prefix = f"{root.val}"
        else:
            new_prefix = prefix + f"->{root.val}"
        
        if root.left is None and root.right is None:
            return [new_prefix]
        
        paths = []
        if root.left is not None:
            paths += self.binaryTreePaths(root.left, new_prefix)
        if root.right is not None:
            paths += self.binaryTreePaths(root.right, new_prefix)
        
        return paths

这一题怎么会被分到简单一栏,完全超出能力范围好吗,不过这一题也让我学到了一个新东西:

f""表示方法,可以将双引号内的表达式变为字符形式,下面是代码示例:

>>> a=f"123"
>>> a
'123'
>>> type(a)

>>> 

你可能感兴趣的:(leetcode刷题笔记,python,leetcode)