Python preorder


  • 0
    def serialize(self, root):
            ans = ''
            stack = [root]
            while stack:
                top = stack.pop()
                if not top:
                    ans = ans + 'None '
                else:
                    ans = ans + str(top.val) + ' '
                    stack.append(top.right)
                    stack.append(top.left)
            return ans
                
        def deserialize(self, data):
            iterator = iter(data.split())
            def buildTree():
                try:
                    node = iterator.next()
                except:
                    return
                if node == 'None':
                    return None
                ans = TreeNode(int(node))
                ans.left = buildTree()
                ans.right = buildTree()
                return ans
            return buildTree()  
    

Log in to reply
 

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