Exercise using python coroutines

  • 0

    I just learned about coroutines and thought that it would be fun to use them, Can definitely be made simpler.
    Idea: Recursively traverse down the tree, Output 'L' before traversing left, 'R' before traversing right, 'U' before going back up.

    class Codec:
        def serialize_coroutine(self, root):
            yield (root.val)
            if root.left != None:
                yield ('L')
                for token in self.serialize_coroutine(root.left):
                    yield token
            if root.right != None:
                yield ('R')
                for token in self.serialize_coroutine(root.right):
                    yield token
        def serialize(self, root):
            if root == None:
                return ''
            return ' '.join([str(num) for num in self.serialize_coroutine(root)])
        def deserialize_coroutine(self, root):
            token = (yield)
            if token == 'L':
                root.left = TreeNode(int((yield)))
                d = self.deserialize_coroutine(root.left)
                token = (yield)
                while d.send(token) != 'D':
                    token = (yield)
                token = (yield)
            if token == 'R':
                root.right = TreeNode(int((yield)))
                d = self.deserialize_coroutine(root.right)
                token = (yield)
                while d.send(token) != 'D':
                    token = (yield)
                token = (yield)
            if token == 'U':
                yield 'D'
        def deserialize(self, data):
            if data == '':
                return None
            tokens = data.split()
            root = TreeNode(int(tokens[0]))
            d = self.deserialize_coroutine(root)
            for token in tokens[1:]:
            return root

Log in to reply

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