leetcode-mid-design-297. Serialize and Deserialize Binary Tree¶-NO -??

mycode

将list转换成树的时候没有思路

参考:

deque 是双边队列(double-ended queue),具有队列和栈的性质,在 list 的基础上增加了移动、旋转和增删等

class Codec:

    def serialize(self, root):
        """Encodes a tree to a single string.
        
        :type root: TreeNode
        :rtype: str
        """
        vals = []
        def preOrder(root):
            if not root:
                vals.append('#')
            else:
                vals.append(str(root.val))
                preOrder(root.left)
                preOrder(root.right)
        preOrder(root)
        return ' '.join(vals)

    def deserialize(self, data):
        """Decodes your encoded data to tree.

        :type data: str
        :rtype: TreeNode
        """
        vals = collections.deque(val for val in data.split())
        def build():
            if vals:
                val = vals.popleft()
                if val == '#':
                    return None
                root = TreeNode(int(val))
                root.left = build()
                root.right = build()
                return root
        return build()
 
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))

其中queue可以用list替换

    def deserialize(self, data):
        """Decodes your encoded data to tree.

        :type data: str
        :rtype: TreeNode
        """
        print(data)
        self.vals = [val for val in data.split()]
        print(self.vals)
        def build():
            if self.vals:
                val = self.vals[0]
                self.vals = self.vals[1:]
                
                if val == '#':
                    return None
                root = TreeNode(int(val))
                root.left = build()
                root.right = build()
                return root
        return build()

疑惑

    def deserialize(self, data):
        """Decodes your encoded data to tree.

        :type data: str
        :rtype: TreeNode
        """
        print(data)
        vals = [val for val in data.split()]
        print(self.vals)
        def build():
            if vals:
                val = vals[0]
                vals[:] = vals[1:]
                print(vals)
                if val == '#':
                    return None
                root = TreeNode(int(val))
                root.left = build()
                root.right = build()
                return root
        return build()
Line 35: AttributeError: Codec instance has no attribute 'vals'
 

猜你喜欢

转载自www.cnblogs.com/rosyYY/p/10980268.html