r/DailyCodingProblem • u/T4ll1n • Mar 29 '22
Daily Coding Problem: Problem #3 [Medium] - 2022-03-29
This problem was asked by Google.
Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree.
For example, given the following Node class
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
The following test should pass:
node = Node('root', Node('left', Node('left.left')), Node('right'))
assert deserialize(serialize(node)).left.left.val == 'left.left'
1
Upvotes
1
u/T4ll1n Mar 29 '22
This one was quite hard for me compared to the previous two that where done in 15minutes.
It took a short time to understand I can use json for the serialization and deserialization, but figuring out the recursive function setup was hard.
It helped A LOT to add the type hints to the function to figure out what input gets created where and how.
I bet there is a cleaner solution for that problem.
Here is my code: