Another pythpon solution


  • 0
    J
    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Codec:
    
        def serialize(self, root):
            """Encodes a tree to a single string.
            
            :type root: TreeNode
            :rtype: str
            """
            if root == None:
                return '[]'
            fringe = [root]
            
            s = '['
            
            while fringe != []:
                node = fringe.pop(0)
                s += str(node.val) + ',' if node else 'null,'
                
                if node:
                    fringe.append(node.left)
                    fringe.append(node.right)
            return s[:-1] + ']'
            
            
    
        def deserialize(self, data):
            """Decodes your encoded data to tree.
            
            :type data: str
            :rtype: TreeNode
            """
            if data == '[]':
                return None
        
            nodes = [None if n == 'null' else int(n) for n in data[1:-1].split(',')]
            
            root = TreeNode(nodes.pop(0))
            fringe = [root]
            while fringe != [] and nodes != []:
                curr_node = fringe.pop(0)
                
                left_val = nodes.pop(0)
                if left_val != None:
                    curr_node.left = TreeNode(left_val)
                    fringe.append(curr_node.left)
                
                right_val = nodes.pop(0)
                if right_val != None:
                    curr_node.right = TreeNode(right_val)
                    fringe.append(curr_node.right)
                    
            return root                
    
    # Your Codec object will be instantiated and called as such:
    # codec = Codec()
    # codec.deserialize(codec.serialize(root))
    

Log in to reply
 

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