알고리즘/트리
트리의 직렬화
jwjwvison
2022. 5. 2. 18:16
https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
Serialize and Deserialize Binary Tree - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
BFS를 통해서 직렬화를 구현해보자.
# 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
"""
queue=collections.deque([(root)])
result=' '.join(result)
while queue:
node=queue.popleft()
if node:
queue.append(node.left)
queue.append(node.right)
result.append(str(node.val))
else:
result.append('#')
return result