【LeetCode】297. Serialize and Deserialize Binary Tree解題レポート(Python)


【LeetCode】297. Serialize and Deserialize Binary Tree解題レポート(Python)
ラベル:LeetCode
タイトルアドレス:https://leetcode.com/problems/serialize-and-deserialize-binary-tree/description/
タイトルの説明:
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
For example, you may serialize the following tree
    1
   / \
  2   3
     / \
    4   5

as “[1,2,3,null,null,4,5]”, just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
テーマの大意
シーケンス化、解シーケンス化二叉木.
解題方法
および449.Serialize and Deserialize BSTはどんなに似ていますか.前に私が言ったように、前序遍歴だけでは木を確定することはできません.私の言うことは厳密ではありません.前のシーケンスのループ中に空のノードが記録されている場合は、このツリーを特定できます.LeetCodeの公式ツリーの構築はこのようなものです.
したがって,我々は問題と同様の方法を採用しているが,空のノードを記録する必要があるだけである.その後、逆シーケンス化時に空のノードに変更すればよい.
# 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
        """
        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))

日付
2018年3月15日–スモッグが消え、春が明るくなった.