Clean python code

  • 3
    class Codec(object):
        def buildNode(self, val):
            return TreeNode(int(val)) if val != 'x' else None
        # return something like 1:2:3:x:x:4:5:x:x:x:x
        def serialize(self, root):
            queue = [root]
            [map(queue.append, (node.left, node.right)) for node in queue if node]
            return ':'.join(map(lambda n: n and str(n.val) or 'x', queue))
        def deserialize(self, data):
            queue, i, data = collections.deque(), 0, data.split(':')
            while i < len(data):
                if not queue:
                    root = self.buildNode(data[i])
                    i += 1
                for _ in xrange(len(queue)):
                    node = queue.popleft()
                    node.left, node.right = [
                        self.buildNode(data[i + j]) for j in xrange(2)]
                    [queue.append(c) for c in (node.left, node.right) if c]
                    i += 2
            return root

  • 0

    can you explain why map(lambda n: n and str(n.val) or 'x', queue) could work? I feel like the lambda function would only return True or False for each node in the queue. (of course I am wrong)

Log in to reply

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