Exercise using python coroutines


  • 0
    L

    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
            yield('U')
    
        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)
                d.send(None)
                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)
                d.send(None)
                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)
            next(d)
            for token in tokens[1:]:
                d.send(token)
            return root
    

Log in to reply
 

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