LC257. 二叉树的所有路径

隐含回溯,先序遍历类似

class Solution(object):
    def binaryTreePaths(self, root):
        """
        :type root: TreeNode
        :rtype: List[str]
        """
        res,sol = [],""
        def backtrack(root,sol):
            if root:
                sol += str(root.val)
                if not root.left and not root.right:
                    res.append(sol[:])
                    return
                else:
                    sol += "->"
                    backtrack(root.left,sol)
                    backtrack(root.right,sol)
                    return
        backtrack(root,sol)
        return res

标准回溯

def binaryTreePaths(self, root):
    """
    :type root: TreeNode
    :rtype: List[str]
    """
    res = []
    path = []
    def backTracking(root):
        path.append(root.val)
        if not root.left and not root.right:
            res.append('->'.join(str(item) for item in path))
            return
        if root.left:
            backTracking(root.left)
            path.pop()
        if root.right:
            backTracking(root.right)
            path.pop()
    backTracking(root)
    return res

你可能感兴趣的:(LC回溯,深度优先,leetcode,算法)