Python backtracking solution, O(logN) space complexity


  • 0
    F
    class Solution:
        # @param {TreeNode} root
        # @return {string[]}
        def binaryTreePaths(self, root):
            def buildstr(node, arr):
                if not node.left and not node.right:
                    arr.append(str(node.val))
                    result.append('->'.join(arr))
                    arr.pop()
                arr.append(str(node.val))
                if node.left:
                    buildstr(node.left, arr)
                    arr.pop()
                if node.right:
                    buildstr(node.right, arr)
                    arr.pop()
                
            result = []
            if not root:
                return result
            buildstr(root, [])
            return result
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.