Interview Question
SDE-3sCountry: India
Interview Type: In-Person
import java.io.*;
public class SerializeAndDeserialize {
public static void serialize(BufferedWriter writer, Node root) throws IOException {
if (root == null) return;
writer.write(root.value);
if (root.left == null && root.right == null){writer.write('*');writer.write('*'); return;}
if (root.left == null) writer.write('*'); else serialize(writer, root.left);
if (root.right == null) writer.write('*'); else serialize(writer, root.right);
}
public static Node deserialize(BufferedReader reader) throws IOException {
int value = reader.read();
if (value < 0 || value == '*') return null;
Node temp = new Node (value);
temp.left = deserialize(reader);
temp.right = deserialize(reader);
return temp;
}
I am assuming the question was referring a BST. You can store the three basically in pre-order, in-order and post-order.
If you store the Tree in an in-order fashion you are basically storing the values sorted, in that case you can modify the file without having to rewrite the tree again.
Example:
Let's say you add 2 on the tree in order to update the file you only have to iterate until the number three and add it before.
- Fernando June 19, 2017