A collaborative whiteboard stores a decision tree diagram as a binary tree in memory, and needs to save it to localStorage and share it in URLs. Implement a TreeCodec class with two methods:
serialize(root) turns a tree into a string;deserialize(text) rebuilds a tree with the same shape and values.Nodes are { value, left, right }, where value is an integer (possibly negative) and left/right are nodes or null.
// 1
// / \
// 2 3
// / \
// -4 5
const codec = new TreeCodec();
const text = codec.serialize(root); // any string format you like
const copy = codec.deserialize(text); // a new tree, structurally equal to root
codec.deserialize(codec.serialize(null)); // null
deserialize(serialize(tree)) must produce a tree that is deeply equal to the original. Shape matters: a node with only a left child is different from one with only a right child.serialize must be a string. Don't use JSON.stringify on the whole tree (that would make the exercise trivial), though you may use it for individual values if you like.Spotted a mistake or a rights concern? Report an issue