297. Serialize and Deserialize Binary Tree - python3

shsh·2021년 2월 2일
0

leetcode

목록 보기
108/161

297. Serialize and Deserialize Binary Tree

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.

Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

이게 뭘 하는 건지 몰라가지고.. 일단 루션이부터 보고 이해했읍니다.

Solution 1: Runtime: 236 ms - 18.25% / Memory Usage: 18.9 MB - 43.27%

# 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
        """
        # use level order traversal to match LeetCode's serialization format
        flat_bt = []
        queue = collections.deque([root])
        while queue:
            node = queue.pop()
            if node:
                flat_bt.append(str(node.val))
                queue.appendleft(node.left)
                queue.appendleft(node.right)
            else:
                # you can use any char to represent null
                # empty string means test for a non-null node is simply: flat_bt[i]
                flat_bt.append('')
        return ','.join(flat_bt)
    # time:  O(n)
    # space: O(n)

    def deserialize(self, data):
        """Decodes your encoded data to tree.
        
        :type data: str
        :rtype: TreeNode
        """
        if not data:
            return
        flat_bt = data.split(',')
        ans = TreeNode(flat_bt[0])
        queue = collections.deque([ans])
        i = 1
        # when you pop a node, its children will be at i and i+1
        while queue:
            node = queue.pop()
            if i < len(flat_bt) and flat_bt[i]:
                node.left = TreeNode(int(flat_bt[i]))
                queue.appendleft(node.left)
            i += 1
            if i < len(flat_bt) and flat_bt[i]:
                node.right = TreeNode(int(flat_bt[i]))
                queue.appendleft(node.right)
            i += 1
        return ans
    # time:  O(n)
    # space: O(n)

# Your Codec object will be instantiated and called as such:
# ser = Codec()
# deser = Codec()
# ans = deser.deserialize(ser.serialize(root))

serialize 에서는 트리를 string 으로 바꿔주고 deserialize 에서는 string 을 트리로 다시 바꿔준다.

serialize

deque 이용. pop 해주면서 반복문을 돌린다.
val 값을 str 형태로 flat_bt 에 넣어주고 ',' 로 구분자를 넣어서 return

deserialize

',' 단위로 data 를 나누고 첫번째 값을 시작으로 ans 에 트리노드를 만들어준다.
또 deque 를 이용해서 left 와 right 값을 설정해줌

뭔가 serialize 는 level 순회로 풀어도 될 듯...??

profile
Hello, World!

0개의 댓글

관련 채용 정보