Python iterative bfs that beats 87%

  • 0

    The solution uses dict key to track potential end nodes and result string.

    def binaryTreePaths(self, root):
            :type root: TreeNode
            :rtype: List[str]
            if not root:
                return []
            result = {root: str(root.val)}
            stack = [root]
            while stack:
                node = stack.pop()
                if node.left or node.right:
                    if node.left:
                        result[node.left] = result[node] + "->" + str(node.left.val)
                    if node.right:
                        result[node.right] = result[node] + "->" + str(node.right.val)
                    del result[node]
            return result.values()

Log in to reply

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