257. 二叉树的所有路径

# 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 countpaths(self, cur, path, result):
        if not cur:
            return []
        path.append(cur.val)
        if not cur.left and not cur.right:
            spath = '->'.join(map(str, path))
            result.append(spath)
            return 
        if cur.left:
            self.countpaths(cur.left, path, result)
            path.pop()
        if cur.right:
            self.countpaths(cur.right, path, result)
            path.pop()
            

    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        path = []
        result = []
        
        self.countpaths(root, path, result)
        return result
    

你可能感兴趣的:(python)