Python Implementation


  • 0
    M
    class Codec:
        SEPARATOR = ","
    
        def serialize(self, root):
            if root is None:
                return ""
                
            return self.SEPARATOR.join([str(root.val), self.serialize(root.left), self.serialize(root.right)])
    
        def deserialize(self, data):
            if not data:
                return None
            
            return self._deserialize_list(data.split(self.SEPARATOR))
        
        def _deserialize_list(self, data):
            if not data:
                return None
            
            val = data.pop(0)
            if not val:
                return None
            
            node = TreeNode(int(val))
            node.left = self._deserialize_list(data)
            node.right = self._deserialize_list(data)
            return node
    

Log in to reply
 

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