|
| 1 | +# 297. Serialize and Deserialize Binary Tree |
| 2 | + |
| 3 | +## DFS Solution |
| 4 | +- Run-time: O(N) |
| 5 | +- Space: O(N) |
| 6 | +- N = Number of nodes in tree |
| 7 | + |
| 8 | +We cannot reuse the solutions from question #105. or #106 using two traversals because duplicate values are allowed. |
| 9 | +We would need a different method. |
| 10 | + |
| 11 | +A DFS method is probably the easiest method to come up with. |
| 12 | +I chose to use preorder, you can implement this using any of the traversals. |
| 13 | + |
| 14 | +Let's start with serialize(), we can simply traverse via. preorder and construct a list. |
| 15 | +This part is straightforward, however, there is a caveat and that is related to space and how we should represent None nodes. |
| 16 | +We could use a string like 'None' but we can save more space by using an empty string instead, this would require us to use a delimiter. |
| 17 | + |
| 18 | +For deserialize(), using the delimiters, we can get the list of nodes in preorder. |
| 19 | +It would simply be a preorder traversal to reconstruct the tree. |
| 20 | + |
| 21 | +There are some further optimizations that we could've done, like condensing consecutive empty strings together. |
| 22 | +It would be more over engineering at this point but good to mention. |
| 23 | + |
| 24 | +``` |
| 25 | +class Codec: |
| 26 | +
|
| 27 | + curr_idx = 0 |
| 28 | + def serialize(self, root): |
| 29 | + """Encodes a tree to a single string. |
| 30 | +
|
| 31 | + :type root: TreeNode |
| 32 | + :rtype: str |
| 33 | + """ |
| 34 | + def preorder_encode(root): |
| 35 | + if root is None: |
| 36 | + result.append('') |
| 37 | + return |
| 38 | + result.append(str(root.val)) |
| 39 | + preorder_encode(root.left) |
| 40 | + preorder_encode(root.right) |
| 41 | +
|
| 42 | + result = list() |
| 43 | + preorder_encode(root) |
| 44 | + return ','.join(result) |
| 45 | +
|
| 46 | + def deserialize(self, data): |
| 47 | + """Decodes your encoded data to tree. |
| 48 | +
|
| 49 | + :type data: str |
| 50 | + :rtype: TreeNode |
| 51 | + """ |
| 52 | + def preorder_decode(): |
| 53 | + if self.curr_idx > len(tokens) or tokens[self.curr_idx] == '': |
| 54 | + return None |
| 55 | + root = TreeNode(int(tokens[self.curr_idx])) |
| 56 | + self.curr_idx += 1 |
| 57 | + root.left = preorder_decode() |
| 58 | + self.curr_idx += 1 |
| 59 | + root.right = preorder_decode() |
| 60 | + return root |
| 61 | +
|
| 62 | + tokens = data.split(',') |
| 63 | + return preorder_decode() |
| 64 | +``` |
0 commit comments