[LeetCode] 297. Serialize and Deserialize Binary Tree_hard tag: DFS, Divide and Conquer
2021-07-29 22:03 Johnson_强生仔仔 阅读(11) 评论(0) 编辑 收藏 举报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.
Example 1:
Input: root = [1,2,3,null,null,4,5] Output: [1,2,3,null,null,4,5]
Example 2:
Input: root = [] Output: []
Example 3:
Input: root = [1] Output: [1]
Example 4:
Input: root = [1,2] Output: [1,2]
Constraints:
- The number of nodes in the tree is in the range
[0, 104]
. -1000 <= Node.val <= 1000
Ideas:
利用preOrder traversal, (note, ans.append(str(root.val))), 因为我们要用“,”.join 的时候每个元素应该是str。来建立一个full tree, 也就是说如果没有children,那么用None来表示,
然后根据preOrder 的特性, data_queue[0] is root, data_queue[1] is left Child, data_queue[0] is right child, 然后recursive 去call就好。
T: O(n), S: O(n)
# 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 """ ans = [] self.preOrder(root, ans) return ','.join(ans) def preOrder(self, root, ans): if not root: ans.append("#") return ans.append(str(root.val)) self.preOrder(root.left, ans) self.preOrder(root.right, ans)
def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ preorder = collections.deque(data.split(',')) return self.helper(preorder) def helper(self, preorder): if not preorder: return root_val = preorder.popleft() if root_val == '#': return root_val_num = int(root_val) root = TreeNode(root_val_num) root.left = self.helper(preorder) root.right = self.helper(preorder) return root