r/DailyCodingProblem • • 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 comment sorted by

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:


# to serialize the node into a string and then deserialize it back to a node we can use the json format.
# We have to recursively turn all the Node classes into a dict and then we can json.dums() the nested dict.
# After that we can json.loads() the string and recursively turn it back into a Node

# Serialize ###
# if the value is a Node, turn the value into a __dict__

def serialize(node: Node) -> str:
    node_dict = serialize_rec(node.__dict__)
    return json.dumps(node_dict)


def serialize_rec(node: dict) -> dict:
    res = {}
    for k, val in node.items():
        if isinstance(val, Node):
            val = serialize_rec(val.__dict__)
        res[k] = val
    return res


# deserialize ###
def deserialize(serialized_node: str) -> Node:
    node_dict = json.loads(serialized_node)
    return deserialize_rec(Node(**node_dict))


def deserialize_rec(node: Node) -> Node:
    for k, val in node.__dict__.items():
        if isinstance(val, dict):
            node.__setattr__(k, deserialize_rec(dict_to_node(val)))
    return node


def dict_to_node(node_dict: dict) -> Node:
    return Node(**node_dict)


# assert
node = Node('root', Node('left', Node('left.left')), Node('right'))
assert deserialize(serialize(node)).left.left.val == 'left.left'